【问题标题】:GetMethod from a current class returns null当前类的 GetMethod 返回 null
【发布时间】:2017-04-25 11:39:48
【问题描述】:

我有公共静态类MyClass,其中我有2个方法重载(基本上方法重载接受MyType1,另一个重载接受MyType2,这些类型继承自MyTypeBase)。

我从第三个方法 (MyPrivateStaticMethod()) 调用重载之一,它接受泛型 (where TArgs : MyTypeBase),这样我就可以有一个方法 (MyPrivateStaticMethod()) 来处理所有继承相同基的类型输入。

// Get Method
var myPrivateStaticMethod =
    typeof(MyClass)
    .GetMethod(
        "MyPrivateStaticMethod",
        BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
        null,
        new Type[]
        {
            typeof(TArgs),
        },
        null
    );

if (myPrivateStaticMethod == null)
{
    // Handle not overloaded method
}

// Trigger method with needed type
myPrivateStaticMethod.Invoke(
    null, 
    new object[] 
    {
        someVar1, // Let's say this is int
        somevar2  // And this is MyType1 or MyType2, 
                  // depending on what type we do have there
});

问题是我找不到这样的方法。另一方面,如果我通过 LINQ 排队:(...).GetMethods(...).Where(x => x.Name == "MyMethodNameIWantToFind").FirstOrDefault(); 它确实找到了方法, 但问题是它没有找到我需要的超载

(使用正确的类型 - 在我的情况下为 MyType1MyType2,它采用找到的第一个方法(MyType1),因为我在第二个之前声明了这个重载,当我通过 @987654334 时这没有用@ 在运行时到该方法)。

问题:我需要在当前类的签名中找到具有多个参数的私有静态方法。我是否错过了 .GetMethod() 使用中的某些内容?

【问题讨论】:

  • 您正在寻找采用TArgs 类型参数的方法,但随后您使用两个参数(someVar1someVar2)调用它。如果他们使用两个参数,则同时指定它们。
  • 旁注:不需要Where(...).FirstOrDefault()FirstOrDefault(...) 可以正常工作。
  • 您应该使用new Type[] {typeOfFirstArg, typeof(TArgs)},因为现在您正在寻找一种采用TArgs 类型的单个参数的方法,并且没有这样的方法,因此您会得到null
  • @PavelSanatov 而不是更新,只需发布​​带有更新和工作代码的答案,然后为未来的访问者接受它。
  • 顺便说一句,有一个名为 ReflectionMagic 的库可以消除所有这些痛苦:this.AsDynamic().MyPrivateStaticMethod(someVar1,someVar2)

标签: c# linq generics methods


【解决方案1】:

问题出在.GetMethod() 内部的new Type[] {...} 数组上。只定义了一种类型,而不是我传递给 MyPrivateStaticMethod() 方法的对象类型计数。

【讨论】:

    猜你喜欢
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    相关资源
    最近更新 更多