【问题标题】:Declaring a List of types声明类型列表
【发布时间】:2010-12-09 14:23:15
【问题描述】:

我想声明一个包含类型的列表:

List<Type> types = new List<Type>() {Button, TextBox };

这可能吗?

【问题讨论】:

  • 我正在开发一组函数来验证/验证用户在表单中输入的数据。

标签: c# list types


【解决方案1】:

试试这个:

List<Type> types = new List<Type>() { typeof(Button), typeof(TextBox) };

typeof() 运算符用于返回一个类型的System.Type

对于对象实例,您可以调用继承自 Object 的 GetType() 方法。

【讨论】:

  • 将声明更改为使用var,你有我的赞成票。 :P
  • 后代场景的轻微变化:如果您有一个实例/对象并希望将其类型包含在同一个列表中,请使用该对象的 .GetType() 属性——例如请参阅以下 'myButton' 变量用法: Button myBtn = new Button(); List types = new List() { myBtn.GetType(), typeof(TextBox) };
  • 如果在方法体类型之外的其他地方声明了 var 关键字不可用。但是是的,您可以(并且应该)在方法中使用 var。
  • 将 decleration 更改为使用 var,你有我的反对票。 :P
【解决方案2】:

您的代码几乎可以使用它。使用 typeof 而不仅仅是类型的名称。

List<Type> types = new List<Type>() {typeof(Button), typeof(TextBox) };

【讨论】:

    【解决方案3】:

    是的,使用List&lt;System.Type&gt;

    var types = new List<System.Type>();
    

    要将项目添加到列表中,请使用 typeof 关键字。

    types.Add(typeof(Button));
    types.Add(typeof(CheckBox));
    

    【讨论】:

      【解决方案4】:
      List<Type> types = new List<Type>{typeof(String), typeof(Int32) };
      

      你需要使用 typeof 关键字。

      【讨论】:

        【解决方案5】:

        使用类型化的通用列表:

        List<Type> lt = new List<Type>();
        

        【讨论】:

          猜你喜欢
          • 2017-01-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-16
          • 1970-01-01
          • 2015-10-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多