Declaring a List of types

后端 未结 5 1074
悲&欢浪女
悲&欢浪女 2020-12-10 23:53

I want to declare a list containing types basically:

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

is this possible?<

相关标签:
5条回答
  • 2020-12-11 00:37

    Try this:

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

    The typeof() operator is used to return the System.Type of a type.

    For object instances you can call the GetType() method inherited from Object.

    0 讨论(0)
  • 2020-12-11 00:37

    You almost have it with your code. Use typeof and not just the name of the type.

    List<Type> types = new List<Type>() {typeof(Button), typeof(TextBox) };
    
    0 讨论(0)
  • 2020-12-11 00:37
    List<Type> types = new List<Type>{typeof(String), typeof(Int32) };
    

    You need to use the typeof keyword.

    0 讨论(0)
  • 2020-12-11 00:39

    Use a typed generic list:

    List<Type> lt = new List<Type>();
    
    0 讨论(0)
  • 2020-12-11 00:53

    Yes, use List<System.Type>

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

    To add items to the list, use the typeof keyword.

    types.Add(typeof(Button));
    types.Add(typeof(CheckBox));
    
    0 讨论(0)
提交回复
热议问题