问题描述
我在c#一个通用接口,并且几乎总是我同类型之一使用它。我想创建该类型的非通用接口,并使用它
I have one generic interface in c#, and almost always I use it with one of the types. I want to create a non-generic interface for that type and use it.
让我们说,我有以下代码:
Let's say, I've the following code:
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>
,所以我尝试以下方法:
it works well. Most times I need IMyGenericList<IItem>
, so i try the following:
public interface IMyItemsList : IMyGenericList<IItem>
{
}
但我不能让MYLIST实施IMyItemsList一些原因。下面的代码返回一个错误
but I can't make MyList implement IMyItemsList for some reason. The following code returns an error
public class MyList<T> : IMyItemsList, IMyGenericList<T> where T : IItem
{
public IEnumerable<T> GetList()
{
return null;
}
}
说,的IEnumerable<的iItem> ;不落实
。
为什么会这样/我该怎么办这件事?
感谢。
Why is it so/what can I do with this?Thanks.
好,感谢您的回答我想通了,这是不可能做到这一点正是因为我想最初。我将发布关于为什么这是不可能的:)
在这里,另一个问题是:的
Ok, thanks to your answers I figured out it's impossible to do it exactly as I wanted initially. I will post another question on why this is impossible :)Here it is: http://stackoverflow.com/questions/4049702/one-function-implementing-generic-and-non-generic-interface
推荐答案
您具体的例子是行不通的,因为你的类:
You specific example wouldn't work, as your class:
public class MyList<T> : IMyItemsList, IMyGenericList<T> where T : IItem
{
public IEnumerable<T> GetList()
{
return null;
}
}
正试图同时实现的IEnumerable<&的iItem GT;的GetList()
和的IEnumerable< T>的GetList()
,这是两个不同的东西。这首先是明确的iItem
的枚举(按要求通过 IMyItemsList
接口),第二个是可枚举的 T
。
is trying to implement both a IEnumerable<IItem> GetList()
and an IEnumerable<T> GetList()
, which are two different things. This first is explicitly an enumerable of IItem
(as required by your IMyItemsList
interface), and the second is an enumerable of T
.
在这种情况下 T
的类型为的iItem
,但没有明确的iItem
。因此,在编译时,在的IEnumerable<&的iItem GT;的GetList()
不是的IEnumerable< T>的GetList()
所以编译器会正确地抛出一个错误告诉你,的IEnumerable<&的iItem GT; 。的GetList()
不落实
In this scenario T
is of type IItem
but is not explicitly IItem
. Therefore at compile time, the IEnumerable<IItem> GetList()
is not IEnumerable<T> GetList()
so the compiler will correctly throw an error telling you that IEnumerable<IItem> GetList()
is not implemented.
另外一个问题,你会碰到,就是当有人做,会发生什么:
The other problem you will run into, is what happens when somebody does:
var list = new MyList<IItem>();
编译器将尝试建立一个具体的实施 MYLIST<的iItem>
这将有的两个定义的IEnumerable<&的iItem GT; 。的GetList()
我会重新考虑你的设计,用于评估一个奇异的IEnumerable< T> 。的GetList()
I would reconsider your design to evaluate a singular IEnumerable<T> GetList()
.
此外,只是挑剔我的一部分:枚举=清单:P
Also, and just picky on my part: "enumerable" != "list" :P
这篇关于非通用接口为通用的一个代名词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!