English 中文(简体)
1. 具有普遍价值的种姓类型
原标题:Cast value type to generic
  • 时间:2010-01-08 21:52:23
  •  标签:
  • c#
  • generics

我有一个通用的类别,我只需要限制价值类型(int、浮动等)。 我有一种方法,即根据这种类型的测试采用“办法”。 例如:

class MyClass<T>
{
    ...

    private static T ParseEntry(string entry)
    {
        if(typeof(T) == typeof(float))
        {
            return (T) float.Parse(entry);
        }

        if(typeof(T) == typeof(int))
        {
            .... you get the idea
        }
    }
}

Constraining T to struct 我确实希望尽可能避免箱子/箱子。 任何想法?

EDIT:对此稍有了解。 我在一间图书馆注意到,两间教室具有非常相似的特性/方法等。 唯一的差别是数据的基本类型(int或浮动)。 THis导致我设计的是通用设计。 唯一的hang是因为要视特定胎盘或倾角而定,要求采用具体办法。 我可以把它带上箱子/箱子,但我确实希望尽可能避免。

最佳回答

不幸的是,你不能造成描述类型的限制。 例如:

class MyClass<T> where T : int { ... } // won t compile

你可能更不用说限制是struct,但会增加一些时间检查,以确保T在你上课时只是支持的类型之一。 由于你没有说你如何重新计划使用你的班级,因此很难就如何实现更好的类型安全提供替代设计建议。

EDIT:你应研究马克和其他人建议的类型转换器选择。 这似乎好像是走路。

http://www.un.org。 对我来说,一种可能的想法是使<代码>Parse()方法成为代表:Func<string,T>——你在施工期间指派。 这将使你能够:

  1. Avoid the inefficient and awkward if/else logic.
  2. Improve the future use of your class to other value types (structs, BigDecimal, etc)

我指的是:

class MyClass<T>
{
    private readonly Func<string,T> ParseEntry;

    public MyClass( Func<string,T> parser )    
    {
        ParseEntry = parser;
    }
}

public static class AvailableParsers
{
    public static Func<string,int> ParseInt = s => int.Parse( s );
    public static Func<string,float> ParseFloat = s => float.Parse(s);
}

可查阅。 唯一的制约因素是:

  • struct (optional)
  • new() (optional)
  • interface constraint (optional, multiple allows)
  • base class constraint (optional, only one allowed)
  • naked constraints ( such as where T : TResult )
问题回答

我看不出这里的价值。

页: 1 因此,请再做其他改动。

而且,想象你不得不处理原始类型,但你真的想要处理所有障碍——这还是不可能做到的,因为不能保证实施一个称为<条码>的可操作性<>的(想象力)接口,将其输入T。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签