为什么显式类型的泛型委托对于这些数字类型被认为是不明确的

本文关键字:类型 数字 于这些 不明确 认为是 泛型 为什么 | 更新日期: 2023-09-27 18:20:48

我一直在编写一些代码,通过委托来执行实际工作,但遗憾的是,现在需要推导委托的参数化类型,所以我对感兴趣的类型使用了重载函数,但很惊讶地发现下面的示例中有歧义。

我意识到我可以强制转换委托参数来解决歧义,但为什么会出现这种歧义,有没有其他方法可以解决它,而无需在调用CallGotTParam之前显式实例化/强制转换委托?

namespace ConversionAmbiguous
{
    class IntShortDelegate
    {
        delegate void GotTParam<T> (T t);
        static void GotInt32Param(System.Int32 t)
        {
            Console.WriteLine("GotInt32Param: {0}", t);
        }
        static void GotInt16Param(System.Int16 t)
        {
            Console.WriteLine("GotInt16Param: {0}", t);
        }
        void CallGotTParam(GotTParam<System.Int32> dcall)
        {
            dcall(1);
        }
        void CallGotTParam(GotTParam<System.Int16> dcall)
        {
            dcall(2);
        }
        static public void Test()
        {
            IntShortDelegate test = new IntShortDelegate();
            // error CS0121: The call is ambiguous between the following methods or properties: 
            // 'ConversionAmbiguous.IntShortDelegate.CallGotTParam(Quickie.ConversionAmbiguous.IntShortDelegate.GotTParam<int>)' and
            // 'ConversionAmbiguous.IntShortDelegate.CallGotTParam(Quickie.ConversionAmbiguous.IntShortDelegate.GotTParam<short>)'
            test.CallGotTParam(IntShortDelegate.GotInt32Param);
            GotTParam<System.Int32> d32 = IntShortDelegate.GotInt32Param;
            test.CallGotTParam(d32); // This is fine
            test.CallGotTParam(IntShortDelegate.GotInt16Param); // This is fine
        }
    }  // class IntShortDelegate
} // Ends namespace ConversionAmbiguous

根据.Net 3.5 编译

简要介绍了csharp语言规范4.0版第7.5.2节"类型推断"和第7.5.3节。过载解决方案,但还没有时间研究它们。

为什么显式类型的泛型委托对于这些数字类型被认为是不明确的

本身不是答案,但如果以下代码是好的

GotTParam<System.Int32> d32 = IntShortDelegate.GotInt32Param;             
test.CallGotTParam(d32); // This is fine 

你也可以试试这个吗?

var typeDelegate = IntShortDelegate.GotInt32Param;             
test.CallGotTParam(typeDelegate); 

如果这样做有效,您可以在处理编译器怪癖的同时维护代码的泛型类型不可知方面。