c# - Creating a reference to another object -
i want make object stores reference object. have code this:
public partial class form1 : form { int test = 1; store st; public form1() { initializecomponent(); } private void form1_load(object sender, eventargs e) { st = new store(test); } private void button1_click(object sender, eventargs e) { test = 7; } private void button2_click(object sender, eventargs e) { label1.text = convert.tostring((int)st.o); } } public class store { public object o; public store(object obj) { o = obj; } }
if click button2 - can see "1" in label. if click button2 , button1 - still see "1". how should alter code i'll see "7" in case?
when create store
object you're evaluating value of test
variable, , storing that value rather the test variable. if want have way of evaluating variable value later, can use lambda close on variable, since closures in c# close on variables, not values.
public partial class form1 : form { int test = 1; store<string> store; public form1() { initializecomponent(); } private void form1_load(object sender, eventargs e) { store = new store<string>(() => test.tostring()); } private void button1_click(object sender, eventargs e) { test = 7; } private void button2_click(object sender, eventargs e) { label1.text = store.getvalue(); } } public class store<t> { private func<t> function; public store(func<t> function) { this.function = function; } public t getvalue() { return function(); } }
note made few changes names of items in line standard c# conventions, rather having store
expose generator function's field publicly, provide function lets value, , i've made generic, rather using object
, both avoids boxing, , prevents need cast object returned store.
Comments
Post a Comment