A problem with generic method overloading

て烟熏妆下的殇ゞ 提交于 2019-12-02 06:32:33

问题


I have the following methods:

void s<t>(int a, t b)
{
    ...
    ..
    .
}

void s<int>(int a, int b)
{
    ...
    ..
    .
}

void s<long>(int a, long b)
{
    ...
    ..
    .
}

when I want to use it as s<long>(10,10) I see these overrides in tooltip. s<long>(int a,int b); and s<long>(int a,long b);. But, I think i must see just s<long>(int a,long b);.

What's wrong ? I have visual studio 2008 sp1.

Thanks

Update : I have test it in Visual Studio 2010.The result is the same. Update : It seems it is about c# not visual studio.


回答1:


You are trying to provide the type parameters you want in the generic definition directly, which is not going to work. If you wish to have versions of the method that support (for the second parameter) objects of type int, long, and T, declare 2 non-generic method overloads and one generic.

void S(int a, int b)
void S(int a, long b)
void S<T>(int a, T b)

Overload resolution will then call the appropriate method based on the arguments, matching the non-generic versions for exact matches on int or long (you can get the generic version even with a int or long parameter if you explicitly invoke it using a type parameter), otherwise getting the generic version.

Examples:

void S<T>(int a, T b)
{
    Console.WriteLine("generic method");
}

void S(int a, int b)
{
    Console.WriteLine("int overload");
}

void S(int a, long b)
{
    Console.WriteLine("long overload");
}

...

S(10, 10);
S(10, (long)10);
S(10, 10L);
S(10, 10M);
S<int>(10, 10); // uses generic
S<long>(10, 10); // uses generic & implicit conversion

Edit: To expand upon a point mentioned briefly above and further in the comments, the match for the int and long overloads needs to be exact. All other arguments will result in the selection of the generic version. If you do not have an int but want the int overload, you will need to explicitly convert the argument prior to or during the method invocation. ex: S(10, (int)myShort);.

Similarly, if you have two versions of method C

void C(Mammal m) { }
void C<T>(T t) { }

with

class Tiger : Mammal { }

The invocation C(new Tiger()) will result in the generic method being used. If you want the Mammal overload for the Tiger instance, you need a reference via the base class. Such as

Mammal m = new Tiger();
C(m); // uses mammal overload
// or 
Tiger t = new Tiger();
C((Mammal)t); // uses mammal overload


来源:https://stackoverflow.com/questions/6093112/a-problem-with-generic-method-overloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!