谜我:为什么会发生隐式接口实现错误?

时间:2011-10-27 10:39:28

标签: c# .net generics interface abstract

考虑以下代码行:

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; }
}

这给了我以下警告: Error 1 ConsoleApplication1.EnumTest.BaseProductList-T- does not implement interface member ConsoleApplication1.EnumTest.IProductList.GetValueObject(). ConsoleApplication1.EnumTest.BaseProductList-T-.GetValueObject() cannot implement ConsoleApplication1.EnumTest.IProductList.GetValueObject() because it does not have the matching return type of ConsoleApplication1.EnumTest.IProduct

<子>  (错误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无法解决这个问题??

1 个答案:

答案 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中是不受支持的,而且从来没有 - 您的代码中的泛型只是同一问题的另一个例子。