简体   繁体   中英

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 :)

尝试这个:

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

C# does not support Property-Delegates.

You can work with anonymous methods in the way Snake mentioned if you need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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