我正在上以下课程-

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

关于c# - 动态加载对象类型并调用其成员函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6761274/

10-09 02:23