检查C#Action/Lambda/Delegate包含任何代码/语句

Chr*_*ken 4 c# reflection lambda delegates

任何人都可以告诉我是否有办法看一个动作是否包含任何代码?

Action x = new Action(()=>
             {

             });
Run Code Online (Sandbox Code Playgroud)

应该返回false,而

Action x = new Action(()=>
             {
                var x = "i am a string" 
             });
Run Code Online (Sandbox Code Playgroud)

应该回归真实.

也许用反射?

小智 7

也许这会有所帮助:

        Action x = new Action(() =>
        {
            var xx = "i am a string";
        });


        Action x1 = new Action(() =>
        {

        });

        MethodBody mb = x.Method.GetMethodBody();
        MethodBody mb1 = x1.Method.GetMethodBody();

        byte[] b = mb.GetILAsByteArray();
        byte[] b1 = mb1.GetILAsByteArray();
Run Code Online (Sandbox Code Playgroud)

b1(空方法体)只有2个字节,值0和42意味着nopreturn,我想.