Define list of a specific type (not object)

2019-08-04 02:20发布

I have: - an interface : IMyType - some classes implementing it : MyType1 , MyType2 , MyType3

How can I define a list of type IMyType?

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

The above list does not force types to be IMyType type, and I can add any type to the list

2条回答
forever°为你锁心
2楼-- · 2019-08-04 02:50

Simply

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

Will do the trick you don't need any fancy stuff

查看更多
我想做一个坏孩纸
3楼-- · 2019-08-04 02:54
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 { }

If you want determine what's implementation class, you can use obj.GetType() or operator obj is MyType1

查看更多
登录 后发表回答