因此,在上一个问题中,我询问了如何使用公共类和宾果实现通用接口,它可以工作 . 但是,我想要传入的其中一种类型是内置的可空类型之一,例如:int,Guid,String等 .
这是我的界面:
public interface IOurTemplate<T, U>
where T : class
where U : class
{
IEnumerable<T> List();
T Get(U id);
}
所以当我这样实现时:
public class TestInterface : IOurTemplate<MyCustomClass, Int32>
{
public IEnumerable<MyCustomClass> List()
{
throw new NotImplementedException();
}
public MyCustomClass Get(Int32 testID)
{
throw new NotImplementedException();
}
}
我收到错误消息:类型'int'必须是引用类型,以便在泛型类型或方法中使用它作为参数'U' 'TestApp.IOurTemplate'
我试图推断类型Int32?,但同样的错误 . 有任何想法吗?
3 回答
我不会真的这样做,但它可能是让它发挥作用的唯一方法 .
可空类型不满足
class
或struct
约束:您需要将类型U限制为类的任何原因?
仅供参考:
int?
是Nullable<int>
的C#简写 .