【问题标题】:c# string to class from which I can call functionsc#字符串到我可以从中调用函数的类
【发布时间】:2023-04-08 04:24:01
【问题描述】:

initialize a class by string variable in c#?我已经知道如何使用字符串创建一个类

所以我已经拥有的是:

Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);

我想要做的是在这个类上调用一个函数,例如:

class.foo();

这可能吗?如果是怎么样?

【问题讨论】:

    标签: c# activator createinstance


    【解决方案1】:
    Type yourType = Type.GetType("project.start");
    object yourObject = Activator.CreateInstance(yourType);
    
    object result = yourType.GetMethod("foo")
                            .Invoke(yourObject, null);
    

    【讨论】:

      【解决方案2】:

      如果您可以假设该类实现了公开 Foo 方法的接口或基类,则适当地转换该类。

      public interface IFoo
      {
         void Foo();
      }
      

      然后在你的调用代码中你可以这样做:

      var yourType = Type.GetType("project.start");
      var yourObject = (IFoo)Activator.CreateInstance(yourType);
      
      yourType.Foo();
      

      【讨论】:

        【解决方案3】:

        这是可能的,但您必须使用反射或在运行时将 class 强制转换为正确的类型..

        反射示例:

        type.GetMethod("foo").Invoke(class, null);
        

        【讨论】:

          【解决方案4】:

          Activator.CreateInstance 返回object 的类型。如果您在编译时知道类型,则可以使用泛型 CreateInstance。

          Type type = Type.GetType("project.start");
          var class = Activator.CreateInstance<project.start>(type);
          

          【讨论】:

            【解决方案5】:
            var methodInfo = type.GetMethod("foo");
            object result  = methodInfo.Invoke(class,null);
            

            Invoke 方法的第二个参数是方法参数。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-11-05
              相关资源
              最近更新 更多