gpt4 book ai didi

c# - Switch/case 语句中的 String.Empty 生成编译器错误

转载 作者:太空狗 更新时间:2023-10-29 22:30:34 24 4
gpt4 key购买 nike

如果 String.Empty"" 一样好,那么编译器怎么会在 case 语句中抛出 string.Empty ?在我看来,没有什么比 string.Empty 更稳定的了。有人知道吗?谢谢!

switch (filter)
{
case string.Empty: // Compiler error "A constant value is expected"

break;

case "": // It's Okay.
break;

}

最佳答案

您可以这样尝试:

switch(filter ?? String.Empty)

string.Empty 是只读字段,而 "" 是编译时常量。您还可以在此处阅读有关代码项目的文章 String.Empty Internals

//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 = "";

旁注:

当您在方法中提供默认参数值时 (C# 4.0),您也会看到此问题:

void myMethod(string filter = string.Empty){}

以上将导致编译时错误,因为默认值需要是常量。

关于c# - Switch/case 语句中的 String.Empty 生成编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32836504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com