c# - C# 和 "a constant value is expected"中的 switch 语句

标签 c# visual-studio

为什么编译器说第一种情况“需要一个常量值”...第二种情况工作正常...

switch (definingGroup)
{
    case Properties.Settings.Default.OU_HomeOffice:  
        //do something  
        break;
    case "OU=Home Office":  
        //do something
        break;
    default:
        break;
 }

也试过...

switch (definingGroup)
{
    case Properties.Settings.Default.OU_HomeOffice.ToString():  
        //do something
        break;
    case "OU=Home Office":
        //do something
        break;
    default:
        break;
 }

...同样的错误

这是 Properties.Setting 代码

[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("OU=Home Office")]
public string OU_HomeOffice {
    get {
        return ((string)(this["OU_HomeOffice"]));
    }
}

最佳答案

Properties.Settings.Default.OU_HomeOffice 不是常量字符串 - 在编译时已知。 C# switch 语句要求每个 case 都是编译时常量。

(除此之外,这是它知道不会有任何重复项的唯一方法。)

有关详细信息,请参阅 C# 3.0 规范的第 8.7.2 节。

关于c# - C# 和 "a constant value is expected"中的 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/466565/

相关文章:

c# - 当测试并行运行时,FakeItEasy 有时无法创建假货

c# - 在 C# 中读取数组列

c# - 输入 'System.Reflection.TargetException'类型的异常

visual-studio - 基于 VCS 重新打开文件后在 Visual Studio 中恢复绿线更改栏

visual-studio - 网络要点 : Compile all TypeScript files on build doesn't work

c# - 将字符串列表放入 Bson 数组

c# - DataContext - ListView - 刷新 UI - INotifyPropertyChanged

javascript - Visual Studio 编译器 'syntax error' 关于 javascript 的警告

visual-studio-2010 - 如何使用 VS2010 Web 部署包包含其他文件?

xml - 在 Visual Studio 2013 Ultimate 中编辑 XML 文件时无法获得 Intellisense 工作