因此,在前面的一个问题中,我问过关于使用公共类和宾果实现泛型接口的问题,它是有效的。但是,我想传递的类型之一是内置的可空类型,如: 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‘必须是引用类型,才能将其用作泛型类型或方法'TestApp.IOurTemplate’中的参数'U‘
我试图推断Int32?类型,但也有相同的错误。有什么想法吗?
发布于 2009-08-28 03:40:37
我不会真的这么做,但这可能是唯一能让它发挥作用的方法。
public class MyWrapperClass<T> where T : struct
{
public Nullable<T> Item { get; set; }
}
public class MyClass<T> where T : class
{
}发布于 2009-08-28 03:35:26
可空类型不满足class或struct约束:
C#语言规范v3.0 (第10.1.5节:类型参数约束):
引用类型约束指定用于类型参数的类型参数必须是引用类型。所有类类型、接口类型、委托类型、数组类型和类型参数(如下所定义)都满足此约束。value type约束指定用于类型参数的类型参数必须是非空值类型。
所有具有值类型约束的非空结构类型、枚举类型和类型参数都满足此约束。注意,尽管可空类型被归类为值类型,但可空类型(§4.1.10)不满足值类型约束。具有值类型约束的类型参数也不能具有构造函数-约束。。
发布于 2009-08-28 04:56:19
你为什么要把U型限制在类上?
public interface IOurTemplate<T, U>
where T : 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?是C#对Nullable<int>的缩写。
https://stackoverflow.com/questions/1344898
复制相似问题