在重载方法上使用泛型参数

nul*_*ptr 4 c# generics parameters methods

为什么这个程序输出Generic Value而不是Hello world!:

using System;

class Example
{
    public static void Print<T>(T value)
    {
        Console.WriteLine("Generic Value");
    }

    public static void Print(string value)
    {
        Console.WriteLine(value);
    }

    public static void GenericFunc<T>(T value)
    {
        Print(value);
    }

    static void Main()
    {
        GenericFunc("Hello world!");
    }
}
Run Code Online (Sandbox Code Playgroud)

泛型方法参数如何在C#的引擎下翻译?

Lua*_*aan 14

重载解析仅在编译时完成.

由于在编译时GenericFunc<T>不知道是否Tstring其他东西,它只能使用Print<T>(T value)"重载".

使用dynamic,您可以将其更改为动态分派,并获得您期望的行为:

Print((dynamic)value);
Run Code Online (Sandbox Code Playgroud)

这使得重载解析在运行时发生,具有实际的运行时类型value.