重载方法的通用调用
我在尝试调用重载方法时遇到 C# 泛型问题。如果您能帮助我,我将不胜感激。
我打电话给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()
{
String test="Test";
foo(test);
}
}
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()
{
String test="Test";
foo(test);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,对于所有类型都必须确定一次调用。仅当
T
是字符串时,您的String printObject(String o)
才有效 - 否则无效,因此编译器无法将泛型方法绑定到此静态类型方法。Well, which is called has to be determined once for all types. Your
String printObject(String o)
will only be valid ifT
is a string - otherwise not, so the compiler cannot bind the generic method to this statically typed method.