【问题标题】:call compile-time-checked method with dynamic arguments in c#在 C# 中调用带有动态参数的编译时检查方法
【发布时间】:2011-01-13 17:13:25
【问题描述】:

好的,这就是我想做的:

public static void CallStaticMethod(Type myType, String methodName, Object[] parameters)
{
     MethodInfo m = myType.GetMethod(methodName); // make this compile-time safe
     m.Invoke(null, parameters);                  // methodName method is supposed to be static
}

现在,如果“methodName”不存在,myType.GetMethod(methodName) 可能会在运行时失败。
有没有办法让这个编译时安全?
(假设参数正确)

我想以某种方式调用该方法:

CallStaticMethod(()=>MyType.MyMethod(), Object[] parameters)

请注意,这不起作用,因为您需要在 lambda 表达式中指定参数。

换句话说,我需要一个方法的编译时安全句柄。 我可以使用 typeof() 获得一个类型,但是方法是否可行?

【问题讨论】:

    标签: c# dynamic static method-call


    【解决方案1】:

    使用函数指针,即委托。 简单例子:

    delegate int StringIntParse(string value);
    
        public static int Main(string[] args)
        {
            StringIntParse p = int.Parse;
            Console.WriteLine(p("34"));
            Console.WriteLine(p.DynamicInvoke(new object[] { "43" }));
            return 0;
        }
    

    您可以在任何委托上使用 DynamicInvoke,例如:

    static object InvokeAnyDelegate(Delegate d, params object[] args)
    {
        return d.DynamicInvoke(args);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-27
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多