在重载方法上使用通用参数 [英] Using a generic parameter on overloaded methods
问题描述
该程序为什么输出通用值
而不是 Hello world!
:
Why does this program output Generic Value
and not 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!");
}
}
如何在C#的框架下转换通用方法参数?
How is the generic method parameter being translated under the hood of C#?
推荐答案
重载解析仅在编译时完成.
Overload resolution is only done at compile-time.
因为 GenericFunc< T>
在编译时不知道 T
是 string
还是其他东西,所以它只能使用 Print< T>(T值)
重载".
Since GenericFunc<T>
doesn't know whether T
is a string
or something else at compile-time, it can only ever use the Print<T>(T value)
"overload".
使用 dynamic
,您可以将其更改为动态调度,并获得预期的行为:
Using dynamic
, you can change this to a dynamic dispatch, and get the behaviour you expect:
Print((dynamic)value);
这使得过载解析在运行时发生,实际运行时类型为 value
.
This makes the overload resolution happen at runtime, with the actual runtime type of value
.
这篇关于在重载方法上使用通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!