2011-11-22 104 views
1

我: - 接口:IMyType - 一些类实现它:MyType1,MyType2,MyType3定义一个特定类型的列表(不是对象)

我如何定义类型IMyType的名单?

var myList = new List<Type> {typeof (MyType1), typeof (MyType2)}; 

上面所列内容并不强制类型是IMyType类型,我可以添加任何类型的列表

回答

2
class Program 
{ 
    static void Main(string[] args) 
    { 
     IList<IMyType> lst = new List<IMyType>(); 
     lst.Add(new MyType1()); 
     lst.Add(new MyType2()); 
     lst.Add(new MyType3()); 

     foreach (var lstItem in lst) 
     { 
      Console.WriteLine(lstItem.GetType()); 
     } 
    } 
} 
public interface IMyType { } 
public class MyType1 : IMyType { } 
public class MyType2 : IMyType { } 
public class MyType3 : IMyType { } 

如果你想确定什么是实现类,你可以使用obj.GetType()或操作obj是MyType1

+0

感谢的Peter.Actually我想要的类型的列表,而不是一个 – Mehrdad

+0

您必须自定义您的列表,并捕获异常该类型的对象的列表** *添加*方法和**索引**属性。因为您确定C#中的每个类型都继承了Type base –

4

只需

List<IMyType> list = new List<IMyType>(); 

会做的伎俩,你不需要任何花式东西

相关问题