【问题标题】:Define list of a specific type (not object)定义特定类型的列表(不是对象)
【发布时间】:2012-01-03 14:48:00
【问题描述】:

我有: - 一个接口:IMyType - 一些实现它的类:MyType1、MyType2、MyType3

如何定义 IMyType 类型的列表?

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

上面的列表不强制类型为IMyType类型,我可以添加任何类型到列表中

【问题讨论】:

    标签: c# .net oop list object


    【解决方案1】:

    简单

    List<IMyType> list = new List<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 is MyType1

      【讨论】:

      • 谢谢彼得。实际上我想要一个类型列表,而不是该类型的对象列表
      • 您必须自定义列表并在 Add 方法和 Index 属性上捕获异常。因为你确定了 C# 中的每个类型都继承了 Type base
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 2020-01-02
      • 2012-09-06
      • 2015-09-07
      • 2012-11-13
      • 2019-02-13
      • 2012-06-07
      相关资源
      最近更新 更多