此代码会产生以下错误:
Error 1 'ConsoleApplication1.FooBar' does not implement interface member 'ConsoleApplication1.IFoo.Bar'. 'ConsoleApplication1.FooBar.Bar' cannot implement 'ConsoleApplication1.IFoo.Bar' because it does not have the matching return type of 'ConsoleApplication1.IBar'.
interface IBar
{
}
interface IFoo
{
IBar Bar { get; }
}
class FooBar<T> : IFoo where T : IBar
{
public T Bar
{
get { return null; }
}
}
由于 FooBar 类中的 where 关键字,这不应该发生。
我使用 Visual Studio 2013 和 .NET 4.5.1 构建了这个。
最佳答案
这不是错误 - Bar
属性的返回类型应该完全匹配,即 IBar
。 C# 不支持返回类型协变。
您可以显式实现接口(interface):
class FooBar<T> : IFoo where T : IBar
{
public T Bar
{
get { return null; }
}
IFoo.Bar { get { return this.Bar; } }
}
关于c# - 这是 C# 泛型错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22424063/