[英]Using generic types to call overloaded functions
StreamWrite.Write
is overloaded for Int16
, Int32
, Int64
, Double
, Single
, String
and many more. StreamWrite.Write
重载了Int16
, Int32
, Int64
, Double
, Single
, String
等等。
Why do I need to use dynamic? 为什么我需要使用动态? When calling the
WriteList
Method, the compiler knows that it is called for Int32
, String
, ... . 在调用
WriteList
方法时,编译器知道它是为Int32
, String
,...调用的。
So why can't I use e (of type T=Int32 ) directly in StreamWrite.Write
? 那么为什么我不能直接在
StreamWrite.Write
使用e (类型T = Int32 )?
public void WriteList<T>(List<T> list)
{
int count = list.Count();
StreamWriter.Write(count);
foreach(T e in list)
{
dynamic d = e;
StreamWriter.Write(d);
}
}
Because overload resolution (in the absence of dynamic
) happens at compile time, and at compile time, the actual type of T
is unknown, since generics are a runtime feature. 因为重载解析(在没有
dynamic
的情况下)在编译时发生,并且在编译时, T
的实际类型是未知的,因为泛型是运行时特征。
The compiler doesn't know which method token of Write
to include in the IL when compiling WriteList
. 编译
WriteList
时,编译器不知道在IL中包含哪个Write
方法标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.