c#属性返回函数 - 从lambda获取值

时间:2016-11-14 22:28:46

标签: c# lambda delegates generic-lambda

我有一个带有返回函数的属性的类。

public class Demo
{
    public Func<string,int,bool> Something { get; set; }
}

如果我喜欢这个

Demo demo = new Demo();

string target;

demo.Something = (a,b)=>
{
   //in here `a` contains a value.
   //and I want to do:
   target = a;

   return true;
};


 //later in the code target is null
 //target here is null instead of having the value of `a`

如何在lambda中为a目标变量赋值,以便稍后在代码中重用它?

1 个答案:

答案 0 :(得分:0)

 public static void Main(string[] args)
 {
     Demo demo = new Demo();

     string target;

     demo.Something = (a, b) =>
     {
         target = a;
         return true;
     };

     //Call something with params
     demo.Something("foo", 1);
 }