Generic type checking

前端 未结 8 1452
既然无缘
既然无缘 2020-12-22 17:10

Is there a way to enforce/limit the types that are passed to primitives? (bool, int, string, etc.)

Now, I know you can limit the generic typ

8条回答
  •  清歌不尽
    2020-12-22 17:58

    Pretty much what @Lars already said:

    //Force T to be a value (primitive) type.
    public class Class1 where T: struct
    
    //Force T to be a reference type.
    public class Class1 where T: class
    
    //Force T to be a parameterless constructor.
    public class Class1 where T: new()
    

    All work in .NET 2, 3 and 3.5.

提交回复
热议问题