Notification object about setting property's member
Assume we have following pseudocode:
class XY
{
int X { get; set; }
int Y { get; set; }
}
class Foo
{
XY _xy;
XY xy
{
get
{
return _xy;
}
set
{
Write("Foo's XY is set!");
_xy = value;
}
}
}
This works fine as long as I'm doing
Foo foo;
foo.xy = XY(1, 3);
XY temp = foo.xy;
temp.y = 5;
foo.xy = temp;
but doesn't work for:
Foo foo;
foo.xy = XY(1, 3);
foo.xy.y = 5; // no "Foo's XY is set!" here
How the latter can be开发者_如何学编程 achieved? Specifically I mean Lua (with _index/_newindex) but I'm writing example code in C#ish language because I think most people know it well and I believe this is more generic programming problem.
Why would it? You didn't set Foo.xy
. You should implement some kind of notification to the base object if you want to achieve that.
In C# the common pattern is implementing INotifyPropertyChanged
interface on XY
and subscribing Foo
to it.
Example:
class XY: INotifyPropertyChanged
{
public X { get {...} set { _x = value; PropertyChanged("X"); }}
// implementation of interface...
}
class Foo
{
public Foo(XY xy)
{
this._xy = xy;
this._xy.PropertyChanged += delegate { Console.WriteLine("changed"); }
}
}
You are actually calling the "getter" in your example. That's why do you don't see your output.
foo.xy.y = 5
You are not replacing the reference to the variable, you are retrieving it.
精彩评论