C# 在泛型接口中实现可空类型
所以在前面的一个问题中,我问了一个关于用公共类和bingo实现通用接口的问题,它是有效的。但是,我希望传入的类型之一是内置的可为空类型,例如:int、Guid、String等 这是我的界面:C# 在泛型接口中实现可空类型,c#,exception,interface,reference,reference-type,C#,Exception,Interface,Reference,Reference Type,所以在前面的一个问题中,我问了一个关于用公共类和bingo实现通用接口的问题,它是有效的。但是,我希望传入的类型之一是内置的可为空类型,例如:int、Guid、String等 这是我的界面: public interface IOurTemplate<T, U> where T : class where U : class { IEnumerable<T> List(); T Get(U id); } 公共接口IOurTemplate
public interface IOurTemplate<T, U>
where T : class
where U : class
{
IEnumerable<T> List();
T Get(U id);
}
公共接口IOurTemplate
T:在哪里上课
你在哪里上课
{
IEnumerable List();
T获取(U id);
}
因此,当我这样实施时:
public class TestInterface : IOurTemplate<MyCustomClass, Int32>
{
public IEnumerable<MyCustomClass> List()
{
throw new NotImplementedException();
}
public MyCustomClass Get(Int32 testID)
{
throw new NotImplementedException();
}
}
公共类测试接口:IOurTemplate
{
公共IEnumerable列表()
{
抛出新的NotImplementedException();
}
公共MyCustomClass Get(Int32 testID)
{
抛出新的NotImplementedException();
}
}
我收到错误消息:“int”类型必须是引用类型,才能将其用作泛型类型或方法“TestApp.IOurTemplate”中的参数“U”
我试图推断Int32?的类型,但同样的错误。有什么想法吗?可空类型不满足
class
或struct
约束:
C语言规范v3.0(第§10.1.5节:类型参数约束):
引用类型约束指定用于类型参数的类型参数必须是引用类型。所有已知为引用类型(定义如下)的类类型、接口类型、委托类型、数组类型和类型参数都满足此约束。
值类型约束指定用于类型参数的类型参数必须是不可为null的值类型
具有值类型约束的所有不可为null的结构类型、枚举类型和类型参数都满足此约束请注意,尽管被分类为值类型,但可为null的类型(§4.1.10)不满足值类型约束。具有值类型约束的类型参数也不能具有构造函数约束
我真的不会这么做,但这可能是让它发挥作用的唯一方法
public class MyWrapperClass<T> where T : struct
{
public Nullable<T> Item { get; set; }
}
public class MyClass<T> where T : class
{
}
公共类MyWrapperClass,其中T:struct
{
公共可空项{get;set;}
}
公共类MyClass,其中T:class
{
}
有什么原因需要将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();
}
}
公共接口IOurTemplate
T:在哪里上课
{
IEnumerable List();
T获取(U id);
}
公共类测试接口:IOurTemplate
{
公共IEnumerable列表()
{
抛出新的NotImplementedException();
}
公共MyCustomClass Get(Int32?testID)
{
抛出新的NotImplementedException();
}
}
仅供参考:
int?
是Nullable
的C#缩写,您有什么建议?如果您不需要约束,请删除它们。如果只想使用可为null的类型,请添加值类型约束(where T:struct
),并在类定义中使用T?
。拥有这样的规则有什么意义?当然,Nullable应该满足结构约束,因为它是一个结构。@bufjape好吧,它是一个特殊的结构,不满足约束<代码>可空由运行时专门处理:当非空的可空
值被装箱时,它被装箱为T
结构,而不是可空
。当一个null
可为null的值被装箱时,它只返回一个null引用。理由是:想象int?a=零;如果(a==null){…}对象o=a;如果(o==null){…}
,您可能希望一致地执行两个if
主体。事实上,在.NET 2.0早期引入可空类型的Beta中,nullable
只是一个常规结构,?
只是一个用于操纵nullable
值的语法糖。由于这种差异,微软决定将CLR改为专门处理Nullable
。您不能编写自己的MyNullable
struct并获得相同的运行时语义。