定义特定类型(不是对象)的列表 [英] Define list of a specific type (not object)
本文介绍了定义特定类型(不是对象)的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有: -接口:IMyType -一些实现它的类:MyType1,MyType2,MyType3
I have: - an interface : IMyType - some classes implementing it : MyType1 , MyType2 , MyType3
如何定义IMyType类型的列表?
How can I define a list of type IMyType?
var myList = new List<Type> {typeof (MyType1), typeof (MyType2)};
上面的列表并不强制类型为IMyType类型,我可以在列表中添加任何类型
The above list does not force types to be IMyType type, and I can add any type to the list
推荐答案
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 is MyType1
If you want determine what's implementation class, you can use obj.GetType() or operator obj is MyType1
这篇关于定义特定类型(不是对象)的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文