类型可以解析字符串的泛型类

Har*_*lse 6 c# generics where-clause

我想创建一个泛型类,其中类的类型可以解析字符串.

我想用这个类有一个静态函数解析(串)的任何类,如System.Int32,System.Double,也为喜欢的System.Guid类.它们都具有静态Parse功能

所以我的类需要一个where子句,它将我的泛型类型约束为具有Parse函数的类型

我想像这样使用它:

class MyGenericClass<T> : where T : ??? what to do ???
{
     private List<T> addedItems = new List<T>()

     public void Add(T item)
     {
          this.AddedItems.Add(item);
     }

     public void Add(string itemAsTxt) 
     {
         T item = T.Parse(itemAsTxt);
         this.Add(item);
     }
}
Run Code Online (Sandbox Code Playgroud)

在where子句中写什么?

Har*_*lse 5

我对使用反射进行解析的答案感到不满意.

我更喜欢类型安全的解决方案,因此编译器会抱怨缺少Parse函数.

通常,您会约束到具有接口的类.但正如其他人所说,没有共同的界面.想到它我不需要接口,我需要一个我可以调用的功能

所以我的解决方案是坚持创建者会向Parse函数提供一个委托,该委托将解析一个字符串来键入 T

class MyGenericClass<T>
{
    public MyGenericClass(Func<string, T> parseFunc)
    {
         this.parseFunc = parseFunc;
    }

    private readonly Func<string, T> parseFunc;

    public void Add(string txt) 
    {
        this.Add(parseFunc(txt));
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

MyGenericClass<Guid> x = new MyGenericClass<Guid>(txt => Guid.Parse(txt));
MyGenericClass<int> y = new MyGenericClass<int> (txt => System.Int32.Parse(txt));
Run Code Online (Sandbox Code Playgroud)

答案比我想象的要简单