C# automatic casting when calling overloaded function -
let's imagine have following overloaded function:
void dosomething(int x) { ... } void dosomething(float x) { ... } void dosomething(decimal x) { ... } in following method, need call correct overload. how simple implementation like:
void havetodosomething(object data) { if (data int) dosomething((int)data); else if (data float) dosomething((float)data); else if (data decimal) dosomething((decimal)data); } this tedious when there ~20 types check. there better way of doing casting automatically?
something forgot mention: dosomething wouldn't work generics, each type needs handled differently, , know type @ runtime.
you can use reflection can have performance impact:
public class example { void dosomething(int i) { } void dosomething(float i) { } } public static class exampleextensions { public static void dosomethinggeneric(this example example, object objectparam) { var t = objectparam.gettype(); var methods = typeof(example).getmethods().where(_ => _.name == "dosomething"); var methodinfo = methods.single(_ => _.getparameters().first().parametertype == t); methodinfo.invoke(example, new[] { objectparam }); } }
Comments
Post a Comment