猜谜语:为什么会出现隐式接口实现错误?
考虑以下代码行:
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\homes$\k.bakker\视觉 工作室 2010\Projects\ConsoleApplication1\ConsoleApplication1\EnumTest\Program.cs 29 23 TestApp)
但是当我添加这段明确的代码时,它就可以工作了:
IProduct IProductList.GetValueObject()
{
return GetValueObject();
}
为什么 .Net 无法弄清楚这一点!?
Consider the following lines of code:
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; }
}
This gives me the following warning:
(Error 1 'ConsoleApplication1.EnumTest.BaseProductList' does not
implement interface member
'ConsoleApplication1.EnumTest.IProductList.GetValueObject()'.
'ConsoleApplication1.EnumTest.BaseProductList.GetValueObject()'
cannot implement
'ConsoleApplication1.EnumTest.IProductList.GetValueObject()' because
it does not have the matching return type of
'ConsoleApplication1.EnumTest.IProduct'. \cencibel\homes$\k.bakker\visual
studio
2010\Projects\ConsoleApplication1\ConsoleApplication1\EnumTest\Program.cs 29 23 TestApp)
But when I add this explicit piece of code, it works:
IProduct IProductList.GetValueObject()
{
return GetValueObject();
}
Why can't .Net figure this one out!?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
返回
IProduct
的方法与返回 some-type-implementing-IProduct
的方法不相同。您正在尝试使用协变返回类型 - .NET 不支持不支持。基本上它类似于这种情况:
看起来不错,并允许客户端调用 Clone() 并返回强类型值 - 但它没有实现该接口。 .NET 不支持这一点,而且从来没有支持过 - 代码中的泛型只是同一问题的另一个示例。
A method returning
IProduct
is not the same as a method returning some-type-implementing-IProduct
. You're trying to use covariant return types - which .NET doesn't support.Basically it's similar to this situation:
Looks good, and allows clients to call
Clone()
and get back a strongly-typed value - but it doesn't implement the interface. This isn't supported in .NET, and never has been - the generics in your code are just another example of the same problem.