动态加载对象类型并调用其成员函数
本文关键字:成员 函数 调用 加载 对象 类型 动态 | 更新日期: 2023-09-27 18:02:57
我有以下类-
public class A
{
public class ChildClass
{
public string name;
public string GetValue()
{
}
}
}
public Class B
{
string className = "ChildClass";
//I want to create an object of ChildClass here
//and call the GetValue() method
}
我如何在B中实例化ChildClass
并使用我的类名访问其成员?
更新代码-
namespace LoadObjectByName
{
class Program
{
static void Main(string[] args)
{
B obj = new B();
obj.GetVal();
}
}
public class A
{
public class ChildClass
{
public string name;
public string GetValue()
{
return "Invoked!";
}
}
}
public class B
{
public string className = "ChildClass";
public dynamic instance = Activator.CreateInstance(Type.GetType("A.ChildClass"));
public dynamic GetVal()
{
return instance.GetValue();
}
}
}
像这样:
var type = GetType(typeof(A).FullName+"+"+className);
dynamic instance = Activator.CreateInstance(type);
instance.GetValue();
或:
var type = typeof(A).GetNestedType(className);
dynamic instance = Activator.CreateInstance(type);
instance.GetValue();
var t = Type.GetType("A").GetNestedType("ChildClass");
var inst = t.GetConstructor(Type.EmptyTypes).Invoke(new object[] {});
Console.WriteLine(t.GetMethod("GetValue").Invoke(inst, new object[] {}));
动态调用方法:
MethodInfo methodInfo = classType.GetMethod("GetValue");
if (methodInfo != null)
{
methodInfo.Invoke(instance, new object[] { /* method arguments*/ });
}