代码之家  ›  专栏  ›  技术社区  ›  Toshi

正确的过载选择

c#
  •  5
  • Toshi  · 技术社区  · 6 年前

    我有密码

    //this runs 
    string[] s_items = {"0","0"};
    string s_output = string.Format("{0}{1}",s_items);
    
    //this one throws a exception
    int[] i_items = {0,0};          
    string i_output = string.Format("{0}{1}",i_items);
    

    为什么第一个运行,第二个抛出异常? 为什么选择

    int[] 这个 Format(String, Object) 超载

    string[] 这个 Format(String, Object[]) 超载

    2 回复  |  直到 6 年前
        1
  •  7
  •   Damien_The_Unbeliever    6 年前

    string[] 可以转换为 object[] 因为它们都是 引用类型 . 所有参考文献都是“平等的”。这是从第一天起就构建在C语言中的讨厌的(数组)转换之一,不应该存在,但我们没有第1天的泛型和适当的协变/逆变规则。

    int[] 无法转换为 对象[] 因为 int s,第一个数组中实际包含的内容不是引用。

        2
  •  3
  •   Fabulous    6 年前

    从msdn文档中,

    这是编译器重载解决方案的问题。由于编译器无法将整数数组转换为对象数组,因此它将整数数组视为单个参数,因此调用格式(字符串、对象)方法。

    查看更多 here .