c# - Generalize an algorithm that needs to work on different data members -
i have piece of code this:
void somealgorithm(sometype somevar) { somevar.somemember = createsomevalue(); lock(something) { sometype someothervar = something.find(somevar.unrelatedmember); if(someothervar != null) someothervar.somemember = somevar.somemember; } }
(i needed adapt bit posting, please bear me if messed in doing so.)
now need exact piece of code another member of somevar
(which has related, different type) , another creation function. know can take code, copy it, replace few identifiers, , done. feel dirty doing so. feel there should way generalize little algorithm.
i know can pass creation function delegate, don't know how generalize member access , there's issue of members (and creation functions) having different types.
in c++, use member pointers combined templates doing this. member pointers aren't piece of cake use, once had looked weird syntax, i'd done within few minutes. how in c#?
edit: since doesn't seem clear enough, here's other instance of same algorithm looks like:
void someotheralgorithm(someothertype somevar) // 1 change here { somevar.someothermember = createsomeothervalue(); // 2 changes here lock(something) { someothertype someothervar = something.find(somevar.unrelatedmember); if(someothervar != null) someothervar.someothermember = somevar.someothermember; // 2 changes here } }
i hope clarifies this.
you've confused me bit, there. somealgorithm
takes parameter of type sometype
called someothervar
, declares local variable same name (so can't compile is). 2 definitions appears somevar
, someothervar
same type (sometype
), local variable declared var
, isn't entirely clear whether or not.
in comment slaks imply somevar
, someothervar
of different types (even though in part of question quoted talking different members of somevar
while slaks asking 2 variables somevar
, someothervar
). i'm going assume they're different types , someothervar
local variable, not parameter.
based on these assumptions:
void somealgorithm<tmember>( sometype somevar, func<tmember> create, // replaces "createsomevalue" func<sometype, tmember> getter, // replaces "somemember" action<sometype, tmember> setter, // replaces set "somemember" action<someothertype, tmember> setter2) // replaces set "somemember" // on "someothervar" (not necessary // if "someothervar" // same type "somevar") { setter(somevar, create()); lock(something) { someothertype someothervar = something.find(somevar.unrelatedmember); if(someothervar != null) setter2(someothervar, getter(somevar)); } }
for first algorithm, called like:
somealgorithm( somevar, createsomevalue, x => x.somemember, (x, y) => { x.somemember = y; }, (x, y) => { x.somememberofothertype = y; } );
for second:
somealgorithm( somevar, createsomeothervalue, x => x.someothermember, (x, y) => { x.someothermember = y; }, (x, y) => { x.someothermemberofothertype = y; } );
Comments
Post a Comment