【问题标题】:In C#, why is string.Empty a field instead of a constant? [duplicate]在 C# 中,为什么 string.Empty 是字段而不是常量? [复制]
【发布时间】:2011-10-24 08:30:39
【问题描述】:

可能重复:
Why isn't String.Empty a constant?

在 C# 4.0 中为方法参数指定默认值时,我可以使用 "" 但不能使用 string.Empty。如果 string.Empty 可能表示“”以外的其他内容,这将是有意义的,但它是一个常量,只是没有声明为 const。

这只是微软的一个错误,他们无法用 const 清理,因为它对语言来说太核心并且会是一个重大变化?或者是否有正当理由首先将其设为填充字段而不是 const?

【问题讨论】:

    标签: c# .net string constants


    【解决方案1】:

    它不能是文字,否则无法从 String 的本机部分访问。

    cmets(在参考资料中)说:

    // The Empty constant holds the empty string value.
    //We need to call the String constructor so that the compiler doesn't mark this as a literal.
    //Marking this as a literal would mean that it doesn't show up as a field which we can access
    //from native. 
    public static readonly String Empty = "";
    

    【讨论】:

    • 有趣的是,cmets 说“我们需要调用字符串构造函数”但是代码没有调用字符串构造函数。
    猜你喜欢
    • 2010-10-05
    • 2012-12-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2016-07-13
    • 2013-12-27
    相关资源
    最近更新 更多