c# - How to store a reference to a property -
is there way store reference property variable allow me access if accessing objects property, so:
var referencevariable = object.property; referencevariable = "something"; if (object.property == "something") //it worked! yaay!
if so, how go doing that?
edit: bit of clarity, going on:
private void updatecolor(){ if (radiobutton1.checked){ object.color1 = color.red } if (radiobutton2.checked){ object.color2 = color.blue } . . . if (radiobuttonn.checked){ object.colorn = color.colorn } }
this sub-optimal. ideally issue handled in function fires when radio button changed, like...
private void radiobutton_checkchanged(object sender, eventargs e){ //something done here tell program interested in object.color...whatever } private void updatecolor(){ //now know color we're looking at, can in 1 step rather looking @ thousand (i exaggerate of course) radio buttons checked states. }
i hope helps me little bit more...
assuming i'm understanding need correctly, use action<>
delegate set properties. following example code (in windows forms app) uses dictionary
store delegate each radio button. radio buttons share same event handler, retrieves delegate dictionary , sets current delegate in colorsetter
variable. i'm using buttons on form change color, , depending on radio button checked, appropriate color property changed.
public partial class form1 : form { private readonly colorpropertyobject cpo = new colorpropertyobject(); private action<color> colorsetter; private readonly dictionary<radiobutton, action<color>> setterdictionary = new dictionary<radiobutton, action<color>>(); public form1() { initializecomponent(); setterdictionary.add(radiobutton1, c => cpo.color1 = c); setterdictionary.add(radiobutton2, c => cpo.color2 = c); setterdictionary.add(radiobutton3, c => cpo.color3 = c); } private void radiobutton1_checkedchanged(object sender, eventargs e) { colorsetter = setterdictionary[(radiobutton)sender]; } private void button1_click(object sender, eventargs e) { colorsetter(color.blue); } private void button2_click(object sender, eventargs e) { colorsetter(color.black); } private void button3_click(object sender, eventargs e) { colorsetter(color.red); } private void button4_click(object sender, eventargs e) { console.writeline(cpo.color1 + " - " + cpo.color2 + " - " + cpo.color3); } } public class colorpropertyobject { public color color1 { get; set; } public color color2 { get; set; } public color color3 { get; set; } }
Comments
Post a Comment