动态加载对象类型并调用其成员函数

时间:2011-07-20 11:40:00

标签: c# .net

我有以下课程 -

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();
        }
    }
}

3 个答案:

答案 0 :(得分:3)

这样的事情:

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();

答案 1 :(得分:2)

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[] {}));

答案 2 :(得分:1)

动态调用方法:

  MethodInfo methodInfo = classType.GetMethod("GetValue");
  if (methodInfo != null)
  {
      methodInfo.Invoke(instance, new object[] { /* method arguments*/ });
  }