【发布时间】:2017-05-16 20:14:26
【问题描述】:
有一个抽象类和接口:
public abstract class Foo
{
public void DoFoo();
}
public interface IBar
{
void DoBar();
}
我有多个继承自 Foo 的类,但并非所有类都实现了 IBar。我可以声明将被 Foo 和 IBar 约束的泛型类,如下所示:
public class Test<T> where T : Foo, IBar
{
public List<T> ListOfFooThatImplementsIBar;
}
但我想定义一个简单的集合,它将被限制为 Foo 和 IBar,如下所示:
List<Foo and IBar> myList = new List<Foo and IBar>();
有没有办法在 C# 中很好地做到这一点?
【问题讨论】:
-
您为什么想要一个彼此没有任何关系(常用方法/属性)的事物的列表?您不妨使用
List<object>。 -
@itsme86 好点 - 我不确定这里的用例是什么。 T 只能作为
IFoo(以我的示例)访问,它什么都没有。如果 Valery 想确定T是Foo还是IBar,他们将不得不 safe-cast 并检查 null。 -
您可能需要使用
MyList<T> : IList<T> where T : Foo, IBar之类的东西,并使用List<T>作为实现细节。 -
没关系。 @EricLippert 澄清了他对其中一个答案的评论中的意图。我把这个问题解释为关于联合类型。
-
对不起,我迷路了。如果你真的想要这个,为什么不能像
class ListFooAndIBar<T> : List<T> where T : Foo, IBar { }那样子类List<T>?我可以理解为什么在语言中拥有它是一个很好的功能,但我没有理解为什么你想要的东西至少在实际中是不可能的?