【问题标题】:C# make generic method that knows how to call function on "some" classC#制作知道如何在“某些”类上调用函数的通用方法
【发布时间】:2014-07-27 18:44:12
【问题描述】:

是否可以在 c# 中创建通用函数,将某些类和方法(类的)以及方法的参数(可能还有结果类型)作为输入,并创建该类的实例并调用带参数的类并返回结果?

【问题讨论】:

标签: c# generics


【解决方案1】:

是的,这是可能的。你可以通过反射来做到这一点。

这里有一些有用的链接

Create an instance with reflection

How to invoke method with parameters

【讨论】:

    【解决方案2】:

    除非反射是您的绝对选择,否则请使用以下委托之一:

    • Action<T>:会让你执行一个不返回值的方法。有几个重载可以让你传递额外的参数。

    • Func<TResult>:将让您执行返回TResult 类型结果的方法。还有更多的重载可以让你传入额外的参数。它们都遵循Func<T1, T2, T3, TResult> 等语法。

    • 最后,您可以定义自己的委托。

    【讨论】:

      【解决方案3】:

      当然。

      public class MyClass
      {
          public class Test
          {
              public int TestMethod(int a, int b)
              {
                  return a + b;
              }
          }
      
          public static void Main()
          {
              int result = ExecuteMethod<Test, int>("TestMethod", 1, 2);
              Console.Read();
          }
      
          public static TResult ExecuteMethod<TClass, TResult>(string methodName, params object[] parameters)
          {
              // Instantiate the class (requires a default parameterless constructor for the TClass type)
              var instance = Activator.CreateInstance<TClass>();
      
              // Gets method to execute
              var method = typeof(TClass).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance);
      
              // Executes and returns result
              return (TResult)method.Invoke(instance, parameters);
          }
      }
      

      【讨论】:

        【解决方案4】:

        以下是使用反射创建类的实例然后调用该类的方法的方法。

        假设你有一堂课:

        public class MyType
        {
            public void DoSomething()
            {
                // do stuff here
            }
        }
        

        您可以执行以下操作:

        Type instanceType = Type.GetType("MyType");
        object instance = Activator.CreateInstance(instanceType);
        
        MethodInfo method = instanceType.GetMethod("MethodName");
        object returnValue = method.Invoke(instance, new object[] { /* paramaters go here */ });
        

        【讨论】:

          猜你喜欢
          • 2020-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-16
          • 2010-12-14
          • 1970-01-01
          • 2016-10-01
          • 1970-01-01
          相关资源
          最近更新 更多