简体   繁体   English

重载方法的泛型调用

[英]Generic call of overloaded methods

i have a problem with C# generics when trying to call overloaded methods.在尝试调用重载方法时,我遇到了 C# generics 的问题。 I would appreciate if you could help me.如果您能帮助我,我将不胜感激。

i call Example.test()我打电话给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);
    }
 }

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.您的String printObject(String o)仅在T是字符串时才有效 - 否则无效,因此编译器无法将泛型方法绑定到此静态类型方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM