c# - How to refer to the a properties accessor and mutator (getter/setter) -
i wondering if there high performant way refer properties getter or setter. example, how fill in details second example class below
public class example { public example() { action<int> setter = setx; func<int> getter = getx; } public int getx() { return 0; } public void setx(int value){} } public class example2 { public example2() { action<int> setter = ...; func<int> getter = ...; } public int x { get{ return 0; } set{} } }
i know create lamdas myself so: action<int> setter = x => x = x
. 1 of reasons wish compare references in other parts of application. wish use references identify particular property.
for example, want succeed :
var example = new example(); func<int> = example.getx; func<int> somethingelse = example.getx; bool equality = something.equals(somethingelse);
only using properties.
i imagine accomplished reflection, many of these operations occur 30 times second or throughout application, hesitant use solution rather declaring getx , setx methods, though seems clumsy.
the end goal create syntaticly simple way both set field, , inform have been linked has been set, , avoid use of strings accomplish it. here's example not using properties, linkages made additional abstractions
public class example { public event action<delegate> change; int x = 0; public int getx() { return x; } public void setx(int value) { setfield(ref x, value, getx); } protected void setfield<t>(ref t t, t value, func<t> getter) { if (!equalitycomparer<t>.default.equals(getter(), value)) { t = value; if(change != null) change(getter); } } } var example = new example(); example.change += getter => { func<int> getx = example.getx; if (getter.equals(getx)) { this.log("x changed to: " + getx()); } }; example.setx(5); // change logged
i think reflection way this:
public example2() { var prop = this.gettype().getproperty("x"); action<int> setter = (action<int>)delegate.createdelegate(typeof(action<int>), this, prop.getsetmethod()); func<int> getter = (func<int>)delegate.createdelegate(typeof(func<int>), this, prop.getgetmethod()); }
but said, reflection not particularly fast. define internal getters / setters methods , bind those, that's not asking either:
public example2() { action<int> setter = this.getx; func<int> getter = this.setx; } private int getx() { return 0; } private void setx(int value) { } public int x { { return getx(); } set { setx(value); } }
Comments
Post a Comment