Hi All,
How do I call the correct overloaded function given a reference to an object based on the actual type of the object. For example...
class Test
{
object o1 = new object();
object o2 = new string("ABCD");
MyToString(o1);
MyToString(o2);//I want this to call the second overloaded function
void MyToString(object o)
{
Console.WriteLine("MyToString(object) called.");
}
void MyToString(string str)
{
Console.WriteLine("MyToString(string) called.");
}
}
what I mean is there a better option than the following?
if(typeof(o) == typeof(string))
{
MyToString((string)o);
}
else
{
MyToString(o);
}
May be this can be done using reflection?
From stackoverflow
-
Ok as soon as I hit post I remembered this can indeed be done using reflection...
var methInfo = typeof(Test).GetMethod("MyToString", new Type[] {o.GetType()}); methInfo.Invoke(this, new object[] {o});
-
Why not have a toString() function in the actual object itself? That way you can call myObj.toString() and the relative output is given. Then you don't have to do any comparisons.
SDX2000 : This is just an example demonstrating my actual problem. -
You could just use ternary operators to code this using a single clean line of code:
MyToString(o is string ? (string)o : o);
leppie : Does that even compile?leppie : And run like you expect it?GoodEnough : I'm pretty sure it will.
0 comments:
Post a Comment