开发者

Generic call of overloaded methods

开发者 https://www.devze.com 2023-03-01 03:41 出处:网络
i have a problem with C# generics when trying to call overloaded methods. I would appreciate if you could help me.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消