c# - Extension methods with base and sub-classes -
update
requesting re-open because other answers don't have solution, 1 of comments question has solution want accept works scenario.
original question
i having trouble writing extension methods non-abstract base classes , sub-classes select appropriate extension method.
i have simple example below (abstracted bigger project) uses extension method "run". expected output listed in comment next each class.
public class parent { }; // should output "parent" public class childa : parent { }; // should output "child a" public class childb : parent { }; // should output "parent" // expected output: childa, parent, parent public class program { public static void main() { var commands = new list<parent>() { new childa(), new childb(), new parent() }; console.writeline(string.join(", ", commands.select(c => c.run()))); } }
here attempts far, there has cleaner way this:
- no type-checking - results in parent extension method being used exclusively (parent, parent, parent)
- explicit type checking - right output, have explicitly check types each extension possibility (childa, parent, parent)
- attempted convert.changetype dynamic type - run-time exception since extension won't catch dynamic type (no output)
- attempted generic cast reflection - not quite operational yet, not sure if approach valid
list of attempts
public static class extensions { public static string run(this childa model) { return "childa"; } public static string run(this parent model) { return model.run1(); // change test different approaches } public static string run1(this parent model) // no type-checking { return "parent"; } public static string run2(this parent model) // explicitly check sub-types { if (model childa) return ((childa)model).run(); else return "parent"; } public static string run3(this parent model) // attempted dynamic type conversion { if (model.gettype().basetype == typeof(parent)) { dynamic changedobj = convert.changetype(model, model.gettype()); return changedobj.run(); } else return "parent"; } public static string run4(this parent model) // attempted reflected generic type conversion { if (model.gettype().basetype == typeof(parent)) { var method = typeof(extensions).getmethod("cast"); var generic = method.makegenericmethod(new[] { model.gettype() }); //var generic = generic.invoke(new object(), null); //return generic.run(); return "not working yet"; } else return "parent"; } public static t cast<t>(this object input) { return (t) input; } }
creating 2 extension methods parent
, childa
, can move association runtime using dynamic
.
console.writeline(string.join(", ", commands.select(c => extensions.run(c dynamic))));
Comments
Post a Comment