2016-11-14 61 views
0

我有一個類的屬性返回一個函數。c#屬性返回函數 - 從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` 

如何分配的價值爲目標的拉姆達內變量後面的代碼重用呢?

+0

你正確地做到了。但是,'Something'沒有被調用。你只是簡單地定義這個函數。之後編寫'demo.Something(...)'將正確地分配'target' – Rob

+0

@Rob:你以後寫demo.omething()是什麼意思?實際上,當我調試它時,我可以看到'a'的值並被分配給目標變量。但是,委託結束後,目標爲空。 – user2818430

+0

@ user2818430,請顯示更多的代碼。你省略了太多。特別是,顯示調用'demo.Something'的行,以及您在哪裏檢查'target'的值。最好你的代碼實際上應該是可運行的 - 即一個最小的獨立可編譯的例子。 –

回答

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); 
}