简体   繁体   English

用另一个调用包装匿名函数

[英]wrap anonymous function with another call

I have this code in which I am trying to wrap an anonymous function by another call so when it is actually the wrapper's value that is returned and not the original function's. 我有这段代码,我试图通过另一个调用来包装一个匿名函数,以便实际上返回的是包装器的值而不是原始函数的值。

In the code below however I get a NullPointerException in the last call. 但是,在下面的代码中,我在上一次调用中得到了NullPointerException I am sure I am not doing something right, but beats me what it is. 我确定我做的事情不正确,但是击败了我。

class Program
{
    public class MyClass
    {
        public int MyProp { get; set; }
    }

    private static List<Func<MyClass, object>> Calls;

    private static object ExtraCall(int obj)
    {
        var returnVal = 8;

        //do some stuff

        return returnVal;
    }

    static void Main(string[] args)
    {
        Calls = new List<Func<MyClass, object>>();

        Calls.Add(c => c.MyProp);

        Func<MyClass, object> func = c => c.MyProp;
        Calls.Add(c => ExtraCall((int)func(func.Target as MyClass)));

        var obj = new MyClass(){ MyProp = 7 };
        var test1 = Calls[0](obj);
        var test2 = Calls[1](obj);
    }
}

func.Target is null because this delegate doesn't have any instance which it is invoked on. func.Target为null,因为此委托没有调用它的任何实例。 You can try following code: 您可以尝试以下代码:

    Calls.Add(c => ExtraCall((int)func(c)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM