[英]Implementing a Generic Interface and a Non Generic Interface
我有两个合同(一个通用接口和另一个非通用)如下:
public interface IGenericContract<T> where T : class
{
IQueryable<T> GetAll();
}
public interface INonGenericContract
{
string GetFullName(Guid guid);
}
我有一个实现两者的类
public class MyClass<T> :
IGenericContract<T> where T : class, INonGenericContract
{
public IQueryable<T> GetAll()
{
...
}
public string GetFullName(Guid guid)
{
...
}
}
在编译它之前,一切都很好。 但是现在当我尝试使用这个类时,我遇到了这个错误“错误CS0311:类型'字符串'不能用作泛型类型或方法'ConsoleApplication1.MyClass'中的类型参数'T'。没有隐式引用转换来自'string'为'ConsoleApplication1.INonGenericContract'。“
class Program
{
static void Main(string[] args)
{
MyClass<string> myClass = new MyClass<string>(); //Error
}
}
如果我不实施非通用合同,它可以正常工作。 这可能有什么问题?
谢谢
在你的代码中, INonGenericContract
是泛型约束的一部分,因为它放在where
之后。
public class MyClass<T> :
IGenericContract<T> where T : class, INonGenericContract
你可能想要:
public class MyClass<T> :
IGenericContract<T>, INonGenericContract where T : class
你非常接近,你要做的是实现非通用接口,而不是约束。
public class MyClass<T> :
IGenericContract<T>, INonGenericContract where T : class
{
public IQueryable<T> GetAll()
{
return null;
}
public string GetFullName(Guid guid)
{
return null;
}
}
现在你可以做到这一点
MyClass<string> myClass = new MyClass<string>();
根据你的表现
public class MyClass<T> : IGenericContract<T> where T : class, INonGenericContract
T
必须实现INonGenericContract
并且string
不实现它。 简而言之, string
不是MyClass
类的有效参数
如果您正在寻找的是实现IGenericContract<T>
AND INonGenericContract
那么您应该拥有
public class MyClass<T> : INonGenericContract, IGenericContract<T>
因为IGenericContract<T>
已经具有该约束,所以不需要具有where T : class
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.