Create class instance from string

泪湿孤枕 提交于 2019-12-01 06:28:59

You may need to use the assembly qualified name as the argument to Type.GetType

eg AssemblyName.Namespace.ClassName

MSDN Doc on assembly qualified names

You may just be missing the namespace from the classname

Works for me:

class ClassX {}
class classPrefix_x : ClassX {}

public class Program
{
    public static void Main()
    {
        string className = "x";
        ClassX obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className));
        Console.WriteLine(obj);
    }
}

Result:

classPrefix_x

The class you are looking for must not be defined. Are you sure you typed it correctly?

You probably don't have a type of "classPrefix_" plus whatever you have on className. The Type.GetType() call returns null and CreateInstance throws the ArgumentNullException.

This is because the Type.GetType(classHere) didn't find anything, are you sure that the classname you're after exists? Remember it should be prefixed with a namespace if possible, and won't be found in an external assembly unless it's already loaded in the App domain.

It looks like Type.GetType("classPrefix_" + className) is returning null.

This returns null when it cannot find the type. A couple of possible causes are missing namespace, or the assembly the class is in is not loaded yet.

The Api documentation on the method which may give some more insite. http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx

It looks like your Type.GetType("classPrefix_" + className) call is returning a null. This is causing the ArgumentNullException when passed to the CreateInstance method.

Evaluate "classPrefix_" + className and check that you do have a type called what it evaluates to.

You also should be specifying the AssemblyQualifiedName when using the Type.GetType method (ie. the fully qualified type name including the assembly name and namespace).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!