我在 C# 中有一个通用接口,并且几乎总是将它与其中一种类型一起使用。我想为该类型创建一个非通用接口并使用它。
假设我有以下代码:
public interface IMyGenericList<out T> where T : IItem
{
IEnumerable<T> GetList();
}
public class MyList<T> : IMyGenericList<T> where T : IItem
{
public IEnumerable<T> GetList()
{
return null;
}
}
效果很好。大多数时候我需要IMyGenericList<IItem>
,所以我尝试以下操作:
public interface IMyItemsList : IMyGenericList<IItem>
{
}
但由于某种原因我无法使 MyList 实现 IMyItemsList 。以下代码返回错误
public class MyList<T> : IMyItemsList, IMyGenericList<T> where T : IItem
{
public IEnumerable<T> GetList()
{
return null;
}
}
这么说IEnumerable<IItem> is not implemented
.
为什么会这样/我能用这个做什么?
谢谢。
好的,感谢您的回答,我发现不可能完全按照我最初想要的方式去做。我将发布另一个问题来解释为什么这是不可能的:)
这里是:实现通用和非通用接口的一个函数 https://stackoverflow.com/questions/4049702/one-function-implementing-generic-and-non-generic-interface
你的具体例子是行不通的,因为你的班级:
public class MyList<T> : IMyItemsList, IMyGenericList<T> where T : IItem
{
public IEnumerable<T> GetList()
{
return null;
}
}
正在尝试实施IEnumerable<IItem> GetList()
and an IEnumerable<T> GetList()
,这是两个不同的东西。这第一个明确是可枚举的IItem
(根据您的要求IMyItemsList
接口),第二个是可枚举的T
.
在这种情况下T
属于类型IItem
但没有明确IItem
。因此在编译时,IEnumerable<IItem> GetList()
is not IEnumerable<T> GetList()
所以编译器会正确地抛出一个错误告诉你IEnumerable<IItem> GetList()
没有实施。
您将遇到的另一个问题是,当有人这样做时会发生什么:
var list = new MyList<IItem>();
编译器将尝试创建一个具体的实现MyList<IItem>
其中有两个定义IEnumerable<IItem> GetList()
.
我会重新考虑你的设计来评估一个单一的IEnumerable<T> GetList()
.
另外,我只是挑剔:“enumerable”!=“list”:P
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)