Generic methods and method overloading

前端 未结 6 1204
情歌与酒
情歌与酒 2020-11-29 09:30

Method overloading allows us to define many methods with the same name but with a different set of parameters ( thus with the same name but different signature ).

A

6条回答
  •  情书的邮戳
    2020-11-29 09:50

    Yes. MyMethod(int myVal) will be called when the type of the parameter is an int, the generic overload will be called for all other parameter arguments, even when the parameter argument is implicitly convertible to (or is a derived class of) the hardcoded type. Overload resolution will go for the best fit, and the generic overload will resolve to an exact match at compile time.

    Note: You can explicitly invoke the generic overload and use an int by providing the type parameter in the method call, as Steven Sudit points out in his answer.

    short s = 1;
    int i = s;
    MyMethod(s); // Generic
    MyMethod(i); // int
    MyMethod((int)s); // int
    MyMethod(1); // int
    MyMethod(1); // Generic**
    MyMethod(1.0); // Generic
    // etc.
    

提交回复
热议问题