![](/img/trans.png)
[英]Do I need to include the 'this' when using a property name in a closure?
[英]Closure and property
var a = "test";
var @delegate = () => a;
Assert.AreEqual(@delegate(),"test"); //true
a = "12345678"
Assert.AreEqual(@delegate(),"test"); //still true, due to closure.
但是,如果變量a是類級別的屬性,則第二個斷言將返回什么-true或false?
例如,如果不是
string _a;
string a {get {return _a;} set{_a = value;}}
如果a是方法而不是屬性,我知道第二個斷言將為false。
閉包捕獲變量,而不是值。 第二個斷言將是錯誤的。
另外,值得注意的是屬性是方法。 一個get
set
對存取的像這樣的屬性
private string _a;
public string a
{
get { return _a; }
set { _a = value; }
}
實際上產生這樣的代碼
private string _a;
public string get_a()
{
return _a;
}
public void set_a(string value)
{
_a = value;
}
像變量這樣的屬性的使用只是語法糖
它們的行為完全相同。
public void ClosureOverVariable()
{
var a = "x";
Func<string> d = () => a;
Console.WriteLine(d()); // print "x"
a = "y";
Console.WriteLine(d()); // print "y"
}
class Foo
{
public string X { get; set; }
}
public void ClosureOverProperty()
{
var a = new Foo
{
X = "a"
};
Func<string> d = () => a.X;
Console.WriteLine(d()); // prints "a"
a.X = "y";
Console.WriteLine(d()); // print "y"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.