C# Deferred Property Setting -
i working on project need queue number of property changes. let have:
public class foo { string bar { get; set; } int bar1 { get; set } }
i want have code looks like:
//store value set actions in queue foo.setvalue(bar, "abc"); foo.setvalue(bar1, 123); //preview changes foreach(item change in foo.changequeue) { console.write(change.propertyname.tostring()); console.write(change.value.tostring()); } //apply actions foo.commitchanges();
what best way accomplish this?
"type-safe" version uses callbacks. not automatically remove duplicate-settings. not use reflection , property-name errors fail on compilation. method expanded require "name" , remove duplicates using dictionary backing (as per akash's answer) or allow "setter" return value (such success or failure or old value, or whatnot).
interface setter { void apply(); } class setter<t> : setter { public t data; public action<t> setfn; public void apply() { setfn(data); } } list<setter> changequeue = new list<setter>(); void setvalue<t>(action<t> setfn, t data){ changequeue.add(new setter<t> { data = data, setfn = setfn, }); } void applychanges(){ foreach (var s in changequeue){ s.apply(); } } // .. later on setvalue(x => system.console.writeline(x), "hello world!"); applychanges();
this method can trivially used "outside" objects being monitored because operations in potential closures.
happy coding.
Comments
Post a Comment