slo*_*ker 6 c# polymorphism enums design-patterns strategy-pattern
如何在不使用C#中的switch或if语句的情况下处理枚举?
例如
enum Pricemethod
{
Max,
Min,
Average
}
Run Code Online (Sandbox Code Playgroud)
......我有一篇文章
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想避免使用switch语句并使其成为通用语句.
对于特定的Pricemethod,请调用特定的计算并将其返回.
get { return CalculatedPrice(Pricemethod); }
Run Code Online (Sandbox Code Playgroud)
这里使用的模式可能有人有一个很好的实现想法.已经搜索了状态模式,但我不认为这是正确的.
Eri*_*ert 11
我该如何处理枚举不使用
switch或if在C#中的语句?
你没有.枚举只是一种令人愉快的写作语法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,
}
Run Code Online (Sandbox Code Playgroud)
现在你可以说
public decimal Price
{
get { return PriceMethod.Invoke(this.PriceHistory); }
}
Run Code Online (Sandbox Code Playgroud)
用户可以说
myArticle.PriceMethod = PriceMethod.Max;
decimal price = myArticle.Price;
Run Code Online (Sandbox Code Playgroud)
您可以创建一个interface和class实现它的es:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:另一种方法是使用a Dictionary来映射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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3280 次 |
| 最近记录: |