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

杀马特。学长 韩版系。学妹 提交于 2019-11-26 16:25:15

问题


I don't know the thing I am asking is available or not but I just want to know if it exists and how it works. So here is my question:

I have 2-3 custom model class of my own. For example, Customer, Employee and Product. Now I have class name in a string. and based on the class name coming in a string, I have to create its object and return to a VIEW. How could I achieve this?

I know a option of IF ELSE statement but I want to try a better,"Dynamic" way...


回答1:


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.




回答2:


    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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/15449800/create-object-instance-of-a-class-having-its-name-in-string-variable

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