Is there a way to turn a string into a Type object?
Let's say I have this basic string...
string a = "Entity";
And this Type object...
Type t;
Is there 开发者_JAVA百科any way to make this Type object reference the type Entity by reading a
?
Exanple: if a
changes to Prop
, it would create a Type object which references the Prop
type. t
would then be equal to typeof(Prop)
.
Yes. There is a static Type.GetType() method that takes a string and returns a Type object representing the type with the name given by the string.
Understand that this will search all referenced namespaces, and there are several classes named, for instance, "TextBox" (in WFA, WPF and ASP namespaces). So, you must fully qualify your type name in order for the method to get the correct type.
Yes, you can use Type.GetType(string)
.
Note:
The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
Beware the additional remarks on the linked MSDN page.
This will create an instance of the class for you, although you cannot cast it to the type specified (unless you have a base object, or know it implements an interface):
public class Testing
{
private void Test()
{
var name = "A";
var type = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Name == name).FirstOrDefault();
var obj = Activator.CreateInstance(type);
}
}
private class A
{
}
精彩评论