【发布时间】:2018-01-28 16:31:16
【问题描述】:
我有一个基本类和两个嵌套类。其中一个嵌套类正在实现一个接口,其中我有一个带有嵌套对象返回类型的方法签名。
这是我得到的:
A 类
using System;
namespace Nested
{
class A
{
public class Item
{
//Implementation
}
class B : IInterface
{
//
public Item Get()
{
throw new NotImplementedException();
}
}
}
}
A 类接口
namespace Nested
{
internal interface IInterface
{
A.Item Get();
}
}
与泛型相同
B 类
using System;
namespace Nested
{
class A<T>
{
public class Item<T>
{
//Implementation
}
class B<T> : IInterface<T>
{
//
public Item<T> Get()
{
throw new NotImplementedException();
}
}
}
}
B 类接口
namespace Nested
{
internal interface IInterface<T>
{
A<T>.Item<T> Get();
}
}
第一个不使用泛型的代码运行良好。与此相比,带有泛型的示例给了我以下错误:
Class1.cs(13,22): error CS0738: 'A<T>.B<T>' does not implement interface member 'IInterface<T>.Get()'. 'A<T>.B<T>.Get()' cannot implement 'IInterface<T>.Get()' because it does not have the matching return type of 'A<T>.Item<T>
为什么说接口使用 A<T>.Item<T> Get(); 和类 public Item<T> Get() 时返回类型不同?有什么想法吗?
编辑:停止将错误代码格式化为块引用,因为部分内容丢失了。这不是我收到的正确信息。
【问题讨论】:
-
因为
A.Item和A.Item<T>是不同的类型,而你的接口契约是从Get方法返回Item而不是Item<T> -
接口说,它必须返回 A
.Item Get(); -
您收到一条警告,说明问题所在。 在此处提问之前,请注意编译器警告并理解它们。
标签: c# generics inner-classes