【问题标题】:String.Format with null format具有空格式的 String.Format
【发布时间】:2010-10-21 14:30:51
【问题描述】:

谁能解释为什么会发生以下情况:

String.Format(null, "foo") // Returns foo
String.Format((string)null, "foo") // Throws ArgumentNullException:
                                   // Value cannot be null. 
                                   // Parameter name: format

谢谢。

【问题讨论】:

    标签: c# null string.format


    【解决方案1】:

    它调用不同的重载。

    string.Format(null, "");  
    //calls 
    public static string Format(IFormatProvider provider, string format, params object[] args);
    

    MSDN Method Link 如上所述。

    string.Format((string)null, "");
    //Calls (and this one throws ArgumentException)
    public static string Format(string format, object arg0);
    

    MSDN Method Link 如上所述。

    【讨论】:

    • 而且我想我们应该提醒您拿起 RedGate Reflector 的副本,这样查找起来就容易多了。 ;)
    • 嗯...我宁愿去查看 MSDN 文档也不愿深入到 Reflector 中获取此类信息。还是我在某个地方错过了一个笑话(是的,通常反射器很好,每个人都应该拥有它)。
    • 你是说 Lutz Roeder 的反光板? (我还没有接受售罄)
    • 你也可以右击,去定义,它有你需要知道的一切。
    【解决方案2】:

    因为调用哪个重载函数是在编译时根据参数的静态类型确定的:

    String.Format(null, "foo")
    

    使用空的 IFormatProvider 和格式化字符串“foo”调用 String.Format(IFormatProvider, string, params Object[]),这非常好。

    另一方面,

    String.Format((string)null, "foo")
    

    使用 null 作为格式化字符串调用 String.Format(string, object),这会引发异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      相关资源
      最近更新 更多