如何查找声明匿名委托的方法

时间:2015-07-21 05:37:08

标签: c# .net reflection delegates clr

我试图对日志进行一些可疑的调用者分析。无论我最终是否真的想要这样做,我想知道我所寻找的是否可能。如果没有,为什么不呢?因为它似乎应该对我来说。

具体做法是:

    private static Action CreateAnonymousMethod()
    {
        MethodBase declaringMethod = new StackFrame(true).GetMethod();

        return delegate()
        {
            var myFrame = new StackFrame(true);

            // This is *this* anonymous method. I can figure out from the name
            // "<CreateAnonymousMethod>garbage" that when the compiler generated
            // it, it knew the answer, but from the MethodBase itself, I can find
            // no path back to declaringMethod. So this answer is incorrect, but
            // I feel like the data should be around here somewhere.
            MethodBase whatGoesHere = myFrame.GetMethod();

            Assert.AreEqual(declaringMethod, whatGoesHere);
        };
    }

我的目标是我或多或少想要一个&#39; Log&#39;可以走向堆栈并找到调用者的方法。我知道[CallerMemberName]属性等,但是呼叫者成员的声明类型没有相应的属性,并且呼叫者的成员名称只是一个字符串。如果可能的话,我想找到一个合适的会员信息。

因此,我通过StackFrame.GetMethod()找到了来电者的方法,但为了更好的记录,我想检测它是否是匿名代表,而不是或者另外对于匿名代表MemberInfo,请使用声明方法的MemberInfo。

然而,我似乎无法从这里到达那里。&#39;最令人沮丧的是,我知道编译器至少在编译时知道,给定匿名委托的名称,但我似乎无法在运行时找到返回MemberInfo的方法。

似乎我想要一些像MemberInfo.DeclaringMember这样的发明属性,这将使匿名方法返回声明它的成员。然而,我知道一个匿名的方法甚至不是CLR的东西,所以当你查看反射时,信息就会消失。所以我希望CompilerGeneratedAttribute它会保留原始的源MemberInfo,我可以从属性中提取它,但该属性似乎没有留下任何痕迹。

此时我认为我唯一的选择是非常脆弱地尝试解析匿名方法名称(哈!)然后用它来某种方式搜索相应的MemberInfo。

无论如何,在我放弃并沿着那条路走下去,看看它有多可怕之前,我想我会向StackOverflow的优秀人员抛出一个冰雹玛丽,看看是否有任何天才解决方案我很遗憾,或者,如果我的思维过程存在根本缺陷。

0 个答案:

没有答案