Create object instance of a class having its name in string variable

三世轮回 提交于 2019-11-27 13:35:56

Having the class name in string is not enough to be able to create its instance. As a matter of fact you will need full namespace including class name to create an object.

Assuming you have the following:

string className = "MyClass";
string namespaceName = "MyNamespace.MyInternalNamespace";

Than you you can create an instance of that class, the object of class MyNamespace.MyInternalNamespace.MyClass using either of the following techniques:

var myObj = Activator.CreateInstance(namespaceName, className);

or this:

var myObj = Activator.CreateInstance(Type.GetType(namespaceName + "." + className));

Hope this helps, please let me know if not.

    string frmName = "frmCustomer";
    //WorldCarUI. is the namespace of the form
    Type CAType = Type.GetType("WorldCarUI." + frmName );
    var myObj = Activator.CreateInstance(CAType);
    Form nextForm2 = (Form)myObj;
    nextForm2.Show();

this does works..

Regards Avi

the easiest way is to use Activator. Pass class name to GetType and Create new instance.

ClassInstance s1 = (ClassInstance)Activator.CreateInstance(Type.GetType("App.ClassInstance"));

public class ClassInstance
{
    public string StringData { get; set; }
}

Regards, Nik

Activator class does this job in .net and this technique is very usefull for dependency injection kind of scenarios.

string NameSpace = "ProjectName.YourNameSpace";
string ProbeClass = "CLassName";

ObjectHandle ProberHandle = Activator.CreateInstance(NameSpace, ProbeClass) as ObjectHandle;
ClassName Prober = ProberHandle.Unwrap() as ClassName;

Ensure that you unwrap before type casting otherwise it will give conversion error.

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