简体   繁体   English

如何将属性设置器链接到委托?

[英]How to link a property setter to a delegate?

I would like to give a property setter to a delegate. 我想给一个代表一个属性设置器。 How is this done? 这是怎么做到的?

class A {
  private int count;
  public int Count {
    get { return count; }
    set { count = value; }
  }
}
A a = new A();   
delegate void ChangeCountDelegate(int x);
ChangeCountDelegate dlg = ... ? // should call a.Count = x
ChangeCountDelegate dlg = (int x) => a.Count = x;

// or
ChangeCountDelegate dlg = x => a.Count = x;

// or 
ChangeCountDelegate dlg = new ChangeCountDelegate(delegate(int x) { a.Count = x; } );

// or 
ChangeCountDelegate dlg = new ChangeCountDelegate(int x => a.Count = x);

Or am I thinking to easy? 还是我想轻松一点? :) :)

I'm sure you get the point. 我相信你明白了。

The 3rd one works in .NET 2.0, the others need at least 3.5 :) 第三个适用于.NET 2.0,其他需要至少3.5 :)

尝试这个:

ChangeCountDelegate dlg = v => a.Count = v;

C# does not support Property-Delegates. C#不支持Property-Delegates。

You can work with anonymous methods in the way Snake mentioned if you need to. 如果需要,您可以按照Snake提到的方式使用匿名方法。

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

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