一个List 中包含多个接口

| 有没有一种方法可以在通用类(如List)中定义类型,使其包含仅包含多个接口的对象?可能是类的类型和接口。 例如:
List<myObjectBase, IDisposable, IClonable> myList;
已邀请:
不知道我是否理解正确,但是如何处理:
class MyList<T> : List<T>
  where T : myObjectBase, IDisposable, IClonable
{
}
这样,您只能将从基础派生并实现这些接口的对象添加到列表中。
否。在这种情况下,您将必须通过以下方式表达这一点:
public class CommonStuff : MyObjectBase, IDisposable, IClonable {}
然后您可以编写:
List<CommonStuff> myList;
不,不支持多个通用参数。 这也没有多大意义。使用通用
List<T>
类而不是像
ArrayList
这样的类将没有任何好处。您将失去所有的类型安全好处,并且最终仍然不得不在各处投掷东西。 更好的选择是创建一个复合类,处理所有您想做的事情……然后使用该类:
public class CommonBase : MyBaseClass, ICloneable, IDisposable
{
}
然后将其用作您的通用参数:
var newList = new List<CommonBase>();
一种可能有用的方法是定义接口ISelf ,该接口的一个成员Self只是将\“ this \”返回为T;然后为可能要组合的任何接口IWhatever定义一个继承IWhatever和ISelf 的通用版本IWhatever 。在那种情况下,实现IFoo 和IBar 的类Whizbang将隐式实现ISelf ,IFoo >,IBar >等。实现IFoo和IBar都可以接受IFoo 类型的参数;该参数将实现IFoo;其Self属性将实现IBar。使用此模式实现多个接口的任何对象都可以使用某些或所有接口(以任意顺序列出)转换为给定形式的嵌套接口类型。
以下是添加对我有用的多个接口的最简单解决方案。 List myList =新List ()
myFirstClass m1C = new myFirstClass();
mySecondClass m2C = new mySecondClass();

myList.Add(m1C);
myList.Add(m2C);

foreach (var item in myList)
{
    item.Clone();
    item.Dispose();
}

class myFirstClass : ICommonInterface  
{  
// implement interface methods  
}  

class mySecondClass : ICommonInterface  
{  
// implement interface methods  
}  


interface ICommonInterface : IDisposable, IClonable  
{  
}  


interface IDisposable  
{  
    void Dispose(){}  
}  

interface IClonable     
{  
    void Clone(){}  
}  
您可以使用ArrayList并可以检查此列表中对象的类型-也许更方便。
if(list[i] is Type)

要回复问题请先登录注册