开发者

Dynamically load an object type and call its member function

开发者 https://www.devze.com 2023-03-21 10:13 出处:网络
I\'m having the following classes - public class A { public class ChildClass { public string name; public string GetValue()

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*/ });
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号