将类属性值用于switch语句

时间:2013-05-02 09:35:55

标签: c#

使用生成的protobuf代码(请参阅http://code.google.com/p/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 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;

不工作...... 有人有想法吗?

2 个答案:

答案 0 :(得分:1)

为什么不在这里使用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 }
    };

然后:

public static Color GetColor(int idFruit) {
    if (this.fruitsColorMap.ContainsKey(idFruit) {
        return this.fruitsColorMap[idFruit];
    }
    return Color.White;
}

答案 1 :(得分:0)

switch语句中的case值必须是常量 - 这是switch语句定义的一部分:

switch (expression)
{
   case constant-expression:
      statement
      jump-statement
   [default:
       statement
       jump-statement]
 }

根据Microsoft的switch (C#)文档。

你会注意到constant-expression位。这意味着它可以在编译时确定。因此,这里不允许调用函数(以及对属性属性的引用实际上是伪装的函数调用)。

相关问题