泛型方法重载的问题
我有以下方法:
void s<t>(int a, t b)
{
...
..
.
}
void s<int>(int a, int b)
{
...
..
.
}
void s<long>(int a, long b)
{
...
..
.
}
当我想将其用作 s
时,我会在工具提示中看到这些覆盖。 s
和 s
。但是,我想我必须只看到 s
。
怎么了 ?我有Visual Studio 2008 sp1。
谢谢
更新: 我已经在 Visual Studio 2010 中测试了它。结果是相同的。 更新:它似乎是关于 c# 而不是 Visual Studio。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您试图直接在泛型定义中提供所需的类型参数,这是行不通的。如果您希望该方法的版本支持(对于第二个参数)int、long 和 T 类型的对象,请声明 2 个非泛型方法重载和一个泛型方法重载。
然后,重载解析将根据参数调用适当的方法,匹配非泛型版本以在
int
或long
上精确匹配(您可以如果您使用类型参数显式调用它,则即使使用int
或long
参数也会获取通用版本,否则获取通用版本。示例:
...
编辑:为了扩展上面简要提到的一点以及注释中进一步的内容,
int
和long
重载的匹配需要准确。所有其他参数都将导致选择通用版本。如果您没有 int 但想要 int 重载,则需要在方法调用之前或期间显式转换参数。例如:S(10, (int)myShort);
。同样,如果您有两个版本的方法
C
,
调用
C(new Tiger())
将导致使用通用方法。如果您想要Tiger
实例的Mammal
重载,则需要通过基类进行引用。例如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.Overload resolution will then call the appropriate method based on the arguments, matching the non-generic versions for exact matches on
int
orlong
(you can get the generic version even with aint
orlong
parameter if you explicitly invoke it using a type parameter), otherwise getting the generic version.Examples:
...
Edit: To expand upon a point mentioned briefly above and further in the comments, the match for the
int
andlong
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
with
The invocation
C(new Tiger())
will result in the generic method being used. If you want theMammal
overload for theTiger
instance, you need a reference via the base class. Such as