我在网站上搜索了我需要的答案,但我找不到它......
我有这个:
string sNameOfClass="BusNode";
该类已经存在,并且有自己的属性。
现在我需要做这样的事情,但我不知道如何......
sNameOfClass variable1 = new sNameOfClass()
并在程序中使用varible1
作为正常变量...
所以喜欢
coorinateClass cs = new ks();
cs.a=11;
cs.b=33;
cs.c=55;
任何线索?
提前谢谢
答案 0 :(得分:1)
如果您需要管理具有其名称的类,您可以使用:
//your class name
string sNameOfClass = "YourNameSpace.BusNode";
//create type class from your class name
Type T = Type.GetType(sNameOfClass);
//create new instance of class
var NewInstanse = Activator.CreateInstance(T);
//set property
T.GetProperty("a").SetValue(NewInstanse, 11);
//get value of property
var a = T.GetProperty("a").GetValue(NewInstanse);
答案 1 :(得分:1)
您可以使用Activator.CreateInstance
方法
答案 2 :(得分:0)
string sNameOfClass="BusNode";
switch (sNameOfClass)
{
case "BusNode":
BusNode variable1 = new BusNode()
break;
case "...."
break;
}