简体   繁体   English

使用泛型类型来调用重载函数

[英]Using generic types to call overloaded functions

StreamWrite.Write is overloaded for Int16 , Int32 , Int64 , Double , Single , String and many more. StreamWrite.Write重载了Int16Int32Int64DoubleSingleString等等。

Why do I need to use dynamic? 为什么我需要使用动态? When calling the WriteList Method, the compiler knows that it is called for Int32 , String , ... . 在调用WriteList方法时,编译器知道它是为Int32String ,...调用的。
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM