我认为这有点奇怪,我希望"I“仅仅是一个接口类型,而T是一个类,实现该接口类型(或扩展它)。
似乎要么我无法设置"null“值,要么强制正确地将模板限制为接口类型。
public class MyClass< T, I> where T: I
{
private I myInterface = null; // error here. I have to use "default(I)"
}我是否强迫自己有正确的“接口”?否则,我为什么要使用“默认(I)”?
使用I的原因是T重载了null check操作符(我使用的是Unity3D,因此我必须在接口上检查等式以避免瓶颈。
在现实中我有:
public class MyClass< T, I>: MonoBehaviour, where T: MonoBehaviour, I
{
private I myInterface = null; // error here. I have to use "default(I)"
}发布于 2017-01-23 10:51:58
由于下面的代码是泛型类型参数的有效实现,所以不能100%确定T是类(唯一的类型为空):
MyClass<int, IEquatable<int>> m;但是,使用class约束,它是:
public class MyClass<T, I> where T: I where I : class
{
private I myInterface = null; // <-- now it is valid
}https://stackoverflow.com/questions/41804549
复制相似问题