C# 声明类型列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1615723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaring a List of types
提问by Luiscencio
I want to declare a list containing types basically:
我想基本上声明一个包含类型的列表:
List<Type> types = new List<Type>() {Button, TextBox };
is this possible?
这可能吗?
采纳答案by Yannick Motton
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.
该typeof()
运算符用于返回System.Type
一个类型的。
For object instances you can call the GetType()
method inherited from Object.
对于对象实例,您可以调用GetType()
从 Object 继承的方法。
回答by Matt Brunell
Yes, use List<System.Type>
是的,使用 List<System.Type>
var types = new List<System.Type>();
To add items to the list, use the typeof keyword.
要将项目添加到列表中,请使用 typeof 关键字。
types.Add(typeof(Button));
types.Add(typeof(CheckBox));
回答by 3Dave
Use a typed generic list:
使用类型化的泛型列表:
List<Type> lt = new List<Type>();
回答by Adam Sills
You almost have it with your code. Use typeof and not just the name of the type.
您几乎可以在代码中找到它。使用 typeof 而不仅仅是类型的名称。
List<Type> types = new List<Type>() {typeof(Button), typeof(TextBox) };
回答by Greg
List<Type> types = new List<Type>{typeof(String), typeof(Int32) };
You need to use the typeof keyword.
您需要使用 typeof 关键字。