6

如何在 C# 中不使用 switch 或 if 语句来处理枚举?

例如

enum Pricemethod
{
    Max,
    Min,
    Average
}

...我有一个班级文章

 public class Article 
{
    private List<Double> _pricehistorie;

    public List<Double> Pricehistorie
    {
        get { return _pricehistorie; }
        set { _pricehistorie = value; }
    }

    public Pricemethod Pricemethod { get; set; }

    public double Price
    {
        get {
            switch (Pricemethod)
            {
                case Pricemethod.Average: return Average();
                case Pricemethod.Max: return Max();
                case Pricemethod.Min: return Min();
            }

        }
    }

}

我想避免 switch 语句并使其通用。

对于特定的 Pricemethod 调用特定的 Calculation 并返回它。

get { return CalculatedPrice(Pricemethod); }

在这里使用哪种模式,也许有人有一个很好的实现想法。已经搜索过状态模式,但我认为这不是正确的。

4

2 回答 2

12

如何在 C# 中不使用switchorif语句处理枚举?

你没有。枚举只是一种令人愉快的写作语法const int

考虑这种模式:

public abstract class PriceMethod
{
  // Prevent inheritance from outside.
  private PriceMethod() {}

  public abstract decimal Invoke(IEnumerable<decimal> sequence);

  public static PriceMethod Max = new MaxMethod();

  private sealed class MaxMethod : PriceMethod
  {
    public override decimal Invoke(IEnumerable<decimal> sequence)
    {
      return sequence.Max();
    }
  }

  // etc, 
}

现在你可以说

public decimal Price
{
    get { return PriceMethod.Invoke(this.PriceHistory); }
}

用户可以说

myArticle.PriceMethod = PriceMethod.Max;
decimal price = myArticle.Price;
于 2013-10-22T17:29:24.000 回答
5

您可以创建一个interface, 和classes 来实现它:

public interface IPriceMethod
{
    double Calculate(IList<double> priceHistorie);
}
public class AveragePrice : IPriceMethod
{
    public double Calculate(IList<double> priceHistorie)
    {
        return priceHistorie.Average();
    }
}
// other classes
public class Article 
{
    private List<Double> _pricehistorie;

    public List<Double> Pricehistorie
    {
        get { return _pricehistorie; }
        set { _pricehistorie = value; }
    }

    public IPriceMethod Pricemethod { get; set; }

    public double Price
    {
        get {
            return Pricemethod.Calculate(Pricehistorie);
        }
    }

}

编辑:另一种方法是使用 a Dictionaryto map Funcs,因此您不必为此创建类(此代码基于Servy的代码,后来他删除了他的答案):

public class Article
{
    private static readonly Dictionary<Pricemethod, Func<IEnumerable<double>, double>>
        priceMethods = new Dictionary<Pricemethod, Func<IEnumerable<double>, double>>
        {
            {Pricemethod.Max,ph => ph.Max()},
            {Pricemethod.Min,ph => ph.Min()},
            {Pricemethod.Average,ph => ph.Average()},
        };

    public Pricemethod Pricemethod { get; set; }
    public List<Double> Pricehistory { get; set; }

    public double Price
    {
        get
        {
            return priceMethods[Pricemethod](Pricehistory);
        }
    }
}
于 2013-10-22T17:25:24.927 回答