C# 将字符串转换为类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/493490/
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
Converting a string to a class name
提问by Bob Smith
I have a string variable that represents the name of a custom class. Example:
我有一个表示自定义类名称的字符串变量。例子:
string s = "Customer";
I will need to create an arraylist of customers. So, the syntax needed is:
我需要创建一个客户数组列表。所以,需要的语法是:
List<Customer> cust = new ..
How do I convert the string s to be able to create this arraylist on runtime?
如何转换字符串 s 以便能够在运行时创建此数组列表?
采纳答案by Jon Skeet
Well, for one thing ArrayList
isn't generic... did you mean List<Customer>
?
嗯,一方面ArrayList
不是通用的……你的意思是List<Customer>
?
You can use Type.GetType(string)
to get the Type
object associated with a type by its name. If the assembly isn't either mscorlib or the currently executing type, you'll need to include the assembly name. Either way you'll need the namespace too.
您可以使用它的名称Type.GetType(string)
来获取Type
与类型关联的对象。如果程序集不是 mscorlib 或当前正在执行的类型,则需要包含程序集名称。无论哪种方式,您都需要命名空间。
Are you sure you really need a generic type? Generics mostly provide compile-timetype safety, which clearly you won't have much of if you're finding the type at execution time. You mayfind it useful though...
你确定你真的需要一个泛型类型吗?泛型主要提供编译时类型安全,如果您在执行时找到类型,显然不会有太多的类型安全。你可能会发现它很有用...
Type elementType = Type.GetType("FullyQualifiedName.Of.Customer");
Type listType = typeof(List<>).MakeGenericType(new Type[] { elementType });
object list = Activator.CreateInstance(listType);
If you need to doanything with that list, you may well need to do more generic reflection though... e.g. to call a generic method.
如果你需要对这个列表做任何事情,你可能需要做更多的通用反射……例如调用通用方法。
回答by pezi_pink_squirrel
This is a reflection question. You need to find the type then instantiate an instance of it, something like this:
这是一道反思题。您需要找到类型,然后实例化它的一个实例,如下所示:
Type hai = Type.GetType(classString,true);
Object o = (Activator.CreateInstance(hai)); //Or you could cast here if you already knew the type somehow
or, CreateInstance(assemblyName, className)
或者, CreateInstance(assemblyName, className)
You will need to watch out for namespace/type clashes though, but that will do the trick for a simple scenario.
不过,您需要注意命名空间/类型冲突,但这对于一个简单的场景就可以解决问题。
Also, wrap that in a try/catch! Activator.CreateInstance is scary!
另外,将其包装在 try/catch 中!Activator.CreateInstance 是可怕的!