How can I get generic Type from a string representation?

前端 未结 5 745
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 00:42

I have MyClass.

And then I have this string s = \"MyClass\";. How can I get Type from the string s

5条回答
  •  感动是毒
    2020-11-30 01:32

    Check out Activator.CreateInstance - you can call it with a type

    Activator.CreateInstance(typeof(MyType))
    

    or with an assembly and type name as string

    Activator.CreateInstance("myAssembly", "myType")
    

    This will give you an instance of the type you need.

    If you need the Type rather than the instance, use the Type.GetType() method and the fully qualified name of the type you're interested in, e.g.:

    string s = "System.Text.StringBuilder";
    Type myClassType = Type.GetType(s);
    

    That'll give you the Type in question.

提交回复
热议问题