考虑以下代码行:
public interface IProduct
{
string Name { get; set; }
}
public interface IProductList
{
string Name { get; }
IProduct GetValueObject();
}
public abstract class BaseProductList<T> : IProductList where T : class, IProduct, new()
{
public abstract T GetValueObject();
public string Name { get; set; }
}
这给了我以下警告:
<子> (错误1'ConsoleApplication1.EnumTest.BaseProductList'没有 实现接口成员 'ConsoleApplication1.EnumTest.IProductList.GetValueObject()'。 'ConsoleApplication1.EnumTest.BaseProductList.GetValueObject()' 无法实施 'ConsoleApplication1.EnumTest.IProductList.GetValueObject()'因为 它没有匹配的返回类型 'ConsoleApplication1.EnumTest.IProduct'。 \ cencibel \家园$ \ k.bakker \视觉 工作室 2010 \ Projects \ ConsoleApplication1 \ ConsoleApplication1 \ EnumTest \ Program.cs 29 23 TestApp) 子>
但是当我添加这段明确的代码时,它可以工作:
IProduct IProductList.GetValueObject()
{
return GetValueObject();
}
为什么.Net无法解决这个问题??
答案 0 :(得分:7)
返回IProduct
的方法不与返回some-type-implemented - IProduct
的方法相同。您正在尝试使用covariant return types - .NET不支持。
基本上它与这种情况类似:
// Doesn't compile
class Foo : ICloneable
{
public Foo Clone()
{
return new Foo();
}
}
看起来不错,并允许客户端调用Clone()
并获取强类型值 - 但它不实现接口。这在.NET中是不受支持的,而且从来没有 - 您的代码中的泛型只是同一问题的另一个例子。