在C#和&QUOT switch语句;一个恒定值,预计" [英] switch statement in C# and "a constant value is expected"

查看:118
本文介绍了在C#和&QUOT switch语句;一个恒定值,预计"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么编译器说:一个恒定值,需要为第一种情况......第二种情况下正常工作...

 开关(definingGroup)
{
情况下Properties.Settings.Default.OU_HomeOffice:
//做些什么
中断;
案OU =家庭办公室:
//做些什么
中断;
默认:
中断;
}



也试过...

 开关(definingGroup)
{
的情况下Properties.Settings.Default.OU_HomeOffice.ToString():
//做些什么
断点;
案OU =家庭办公室:
//做些什么
中断;
默认:
中断;
}



...同样的错误



下面是Properties.Setting代码

  [全球:: System.Configuration.ApplicationScopedSettingAttribute()] 
[全球:: System.Diagnostics.DebuggerNonUserCodeAttribute()]
[全球:: System.Configuration.DefaultSettingValueAttribute(OU =家庭办公室)]
公共字符串OU_HomeOffice {
获得{
回报率((字符串)(本[OU_HomeOffice]));
}
}


解决方案

Properties.Settings.Default.OU_HomeOffice 不是一个常量字符串 - 这是在编译时已知。 C#的switch语句要求每一个案件是一个编译时间常数。



(二话不说,就是它可以知道,不会有任何的唯一途径重复。)



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


Why does the compiler say "a constant value is required" for the first case...the second case works fine...

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

also tried...

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

...same error

Here's the Properties.Setting code

[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 isn't a constant string - something known at compile time. The C# switch statement requires that every case is a compile-time constant.

(Apart from anything else, that's the only way it can know that there won't be any duplicates.)

See section 8.7.2 of the C# 3.0 spec for more details.

这篇关于在C#和&QUOT switch语句;一个恒定值,预计"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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