Dynamically load an object type and call its member function
I'm having the following classes -
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
}
How can I instantiate ChildClass
in B and access its members with the class name I've?
Updated Code -
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();
}
}
}
Something like this:
var type = GetType(typeof(A).FullName+"+"+className);
dynamic instance = Activator.CreateInstance(type);
instance.GetValue();
Or:
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[] {}));
Dynamically call a method:
MethodInfo methodInfo = classType.GetMethod("GetValue");
if (methodInfo != null)
{
methodInfo.Invoke(instance, new object[] { /* method arguments*/ });
}
精彩评论