i have a problem with C# generics when trying to call overloaded methods. I would appreciate if you could help me.
i call Example.test()
public class Example
{
private String printObject(Object o)
{
//this is the one that is called
}
private String printObject(String o)
{
//this is the one I expect to be called
}
private void callPrint<T>(Object o)
{
if (o is T)
{
T tmp;
tmp = (T)o;
data = _printObject(tmp);
}
}
public String foo(Object o)
{
callPrint<String>(o);
}
public static void test()开发者_如何学JAVA
{
String test="Test";
foo(test);
}
}
Well, which is called has to be determined once for all types. Your String printObject(String o)
will only be valid if T
is a string - otherwise not, so the compiler cannot bind the generic method to this statically typed method.
精彩评论