A problem with generic method overloading
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开发者_JAVA百科 visual studio.
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
精彩评论