C# 对switch语句使用类属性值
am使用生成的protobuf代码(请参阅) 我有一个生成的类,如下所示:C# 对switch语句使用类属性值,c#,C#,am使用生成的protobuf代码(请参阅) 我有一个生成的类,如下所示: public class Fruits{ private int _ID_BANANA = (int)1; private int _ID_APPLE = (int)2; public int ID_BANANA { get { return _ID_BANANA; } set { _ID_BANANA = value; } } public
public class Fruits{
private int _ID_BANANA = (int)1;
private int _ID_APPLE = (int)2;
public int ID_BANANA
{
get { return _ID_BANANA; }
set { _ID_BANANA = value; }
}
public int ID_APPLE
{
get { return _ID_APPLE; }
set { _ID_APPLE = value; }
}
}
public static Color GetColor(int idFruit) {
switch (idFruit)
{
case new Fruits().ID_BANANA:
return Color.Yellow;
case new Fruits().ID_APPLE:
return Color.Green;
default:
return Color.White;
}
}
然后它们是常量值,但我不能在代码中这样使用它们。
例如,我想做这样一个映射器:
public class Fruits{
private int _ID_BANANA = (int)1;
private int _ID_APPLE = (int)2;
public int ID_BANANA
{
get { return _ID_BANANA; }
set { _ID_BANANA = value; }
}
public int ID_APPLE
{
get { return _ID_APPLE; }
set { _ID_APPLE = value; }
}
}
public static Color GetColor(int idFruit) {
switch (idFruit)
{
case new Fruits().ID_BANANA:
return Color.Yellow;
case new Fruits().ID_APPLE:
return Color.Green;
default:
return Color.White;
}
}
我有一个错误:需要一个常量值
我考虑过创建枚举,但似乎是错误的方法,尝试了以下方法:
public const int AppleId = new Fruits().ID_APPLE;
也不工作。。。
有人有主意了吗?为什么不在这里使用
if-else if
语句
var fruits = new Fruits();
if (idFruit == fruits._ID_BANANA)
return Color.Yellow;
else if (idFruit == fruits._ID_APPLE)
return Color.Green;
else
return Color.White;
或字典:
this.fruitsColorMap = new Dictionary<int, Color>
{
{ fruits._ID_BANANA, Color },
{ fruits._ID_APPLE, Green }
};
switch语句中的case值必须是常量-这是switch语句定义的一部分:
switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
}
根据Microsoft提供的文档
您将注意到
常量表达式
位。这意味着它可以在编译时确定。因此,这里不允许调用函数(而对属性的引用实际上是伪装的函数调用)。private int\u ID\u BANANA=(int)1代码>不是常数。它是一个私有字段,可以在类范围内修改。在给定的示例中,属性\u ID\u BANANA
对其进行修改。第二个字段也是一样。C#编码约定应该遵循您显示的类肯定不会编译的规则。它定义了\u ID\u BANANA
和\u ID\u APPLE
两次。请显示您的真实代码。@PLB这意味着它是一个常数,没有人会更改它。所以,如果您需要,我想要一个枚举,它是一个新实例的“快照”。@Thomas编译器怎么知道程序员会遵守诺言,不会触及这些字段?:)因为这会在不理解的情况下掩盖问题。这对映射方法很有效,但我想在单元测试中使用这些值作为枚举或常量。@Thomas:然后将此属性类型设为enum
,并在switch语句中使用。@Olivier,我无法更改生成的文件。@Sergey Metlov我想在我的代码中以某种方式访问类似以下内容的名称:(int)Myclass.Apple
。如果您是真的,我将使用if语句。