为什么我不能用的String.Empty作为默认的参数值? [英] Why can't I use String.Empty as a default parameter value?

查看:254
本文介绍了为什么我不能用的String.Empty作为默认的参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我被创建在构造函数中默认参数值。

Today I was creating a default parameter value in a constructor.

public SomeClass (String something = String.Empty)
{
   // ...
}

编译器抱怨。

The compiler complained.

有东西默认参数值必须是编译时   恒定的。

Default parameter value for "something" must be a compile-time constant.

我下的是IM pression是空的String类是一个编译时间常数。

I was under the impression that Empty on the String class was a compile-time constant.

.field public static initonly string Empty

我是不是missunderstanding编译时的含义不变,或只是更wackyness,我需要接受吗?

Am I missunderstanding the meaning of compile-time constant, or is it just more wackyness that I need to accept?

推荐答案

在接受答案的,以便问题的为什么没有的String.Empty恒定的是:

The accepted answer to this SO Question Why isn't String.Empty a constant? is:

这是静态只读使用而不是常量的原因是由于与非托管code使用,微软的共享源代码公共语言基础2.0发行所示这里。来看看这个文件是sscli20 \ CLR的\ src \ BCL \ SYSTEM \ string.cs。

The reason that static readonly is used instead of const is due to use with unmanaged code, as indicated by Microsoft here in the Shared Source Common Language Infrastructure 2.0 Release. The file to look at is sscli20\clr\src\bcl\system\string.cs.

在空不变持有空字符串值。我们需要调用String构造这样编译器不标记此为文字。

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.

我觉得从这个方便的文章这些信息在$ C $的CProject。

I found this information from this handy article at CodeProject.

这篇关于为什么我不能用的String.Empty作为默认的参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆