泛型和调用重载方法从不同的类优先问题 [英] Generics and calling overloaded method from difference class - precedence issue

查看:116
本文介绍了泛型和调用重载方法从不同的类优先问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对于标题感到抱歉,但我无法想象任何更好的...



我的问题可以通过简单的代码示例来呈现:

/ p>

public static class Test< T>
{
public static int GetInt(T source)
{
return Convert.ToInt32(source);



public static class转换
{
public static int ToInt32(字节源)
{
return 30 ;
}

public static int ToInt32(object source)
{
return 10;




为什么 Console.WriteLine(Test< byte> .GetInt(20)); 打印 10 ,而不是 30 我一直认为.NET中的泛型在运行时被JIT解决。为什么抖动不够聪明,发现有 ToInt32(byte)方法,它适合我们的字节参数类型在这里吗?



这个行为使得转换静态类方法调用结果在简单类型的装箱/取消装箱操作。

解决方案

编译器必须在编译时决定选择哪种方法。它不会发出任何代码来在运行时决定选择哪个重载。由于您没有向C#编译器提供任何证据,因此 GetInt(T source)仅适用于 byte 结构,编译器必须选择其他重载。



或者让我把它放在另一个角度:如果你移除 ToInt32(object) code> overload,你的程序无法编译。


First of all, sorry for the title, but I couldn't think about anything better ...

My problem can be presented by simple code sample:

public static class Test<T>
{
    public static int GetInt(T source)
    {
        return Convert.ToInt32(source);
    }
}

public static class Convert
{
    public static int ToInt32(byte source)
    {
        return 30;
    }

    public static int ToInt32(object source)
    {
        return 10;
    }
}

Why does Console.WriteLine(Test<byte>.GetInt(20)); prints 10, instead of 30?

I always thought that generics in .NET are resolved by JIT during runtime. Why then jitter isn't smart enough, to find out that there is ToInt32(byte) method, which suits our byte parameter type here?

This behavior makes Convert static class methods call result in boxing/unboxing operations for simple types.

解决方案

The compiler has to decide at compile time which method to choose. It doesn't emit any code to decide at runtime which of the two overloads to pick. Because you haven't provided any evidence to the C# compiler that GetInt(T source) only works with byte structures, the compiler has to pick the other overload.

Or let me put it in a different perspective: if you remove the ToInt32(object) overload, your program fails to compile.

这篇关于泛型和调用重载方法从不同的类优先问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆