我是学生,我想知道有没有一种方法可以为泛型类型指定类型?
例如,我有一个IEntity
接口,如下面的代码
public interface IEntity<T> where T : // What I should input here?
{
public T Id { get; set; }
}
如果我只希望T为int
,string
和Guid
,该怎么办?
我尝试这样做:
public interface IEntity<T> where T : int, string, Guid // Compile Error:
//'int' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
//'string' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
//'Guid' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
{
public T Id { get; set; }
}
我可以将IComparable
,int
和string
的T设置为Guid
,但是某些数据类型(例如float)也可以从IComparable
传递。我只想输入3种类型:int
,string
和Guid
,有能力做到这一点吗?