简体   繁体   中英

Generic call of overloaded methods

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);
    }
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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