对于状态处理多态枚举 [英] Polymorphic Enums for state handling
问题描述
如何处理枚举,而不使用开关或在C#中的语句?
例如
枚举Pricemethod
{
。最大,
敏,
平均
}
...和我有一个一流的文章
公开Article类
{
私有列表<双> _pricehistorie;
公开名单<双> Pricehistorie
{
{返回_pricehistorie; }
集合{_pricehistorie =价值; }
}
公共Pricemethod Pricemethod {搞定;组; }
公共双价
{
获得{
开关(Pricemethod)
{
情况下Pricemethod.Average:平均回报();
情况下Pricemethod.Max:返回MAX();
情况下Pricemethod.Min:返回MIN();
}
}
}
}
我想避免switch语句,并使其通用性。
有关特定Pricemethod调用特定的计算并返回。
{返回CalculatedPrice(Pricemethod); }
至极模式是用在这里,也许有人有一个好主意执行。
搜索已经对国家的模式,但我不认为这是正确的。
做我怎么处理枚举,而无需使用
开关
或如果
在C#中的语句?
块引用>
您没有。 。枚举只是写
const int的
愉快的语法
考虑以下模式:
公共抽象类PriceMethod
{
从外面//防止继承。
私人PriceMethod(){}
公共抽象小数调用(IEnumerable的<&小数GT;序列);
公共静态PriceMethod最大=新MaxMethod();
私人密封类MaxMethod:PriceMethod
{
公众覆盖小数调用(IEnumerable的<十进制>序列)
{
返回sequence.Max();
}
}
//等等,
}
而现在你可以说
公共十进制价格
{
{返回PriceMethod.Invoke(this.PriceHistory); }
}
和用户可以说出
myArticle.PriceMethod = PriceMethod.Max;
十进制价格= myArticle.Price;
how do i handle Enums without using switch or if statements in C#?
For Example
enum Pricemethod { Max, Min, Average }
... and i have a class Article
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(); } } } }
i want to avoid the switch statement and make it generic.
For a specific Pricemethod call a specific Calculation and return it.
get { return CalculatedPrice(Pricemethod); }
Wich pattern is to use here and maybe someone have a good implementation idea. Searched already for state pattern, but i dont think this is the right one.
解决方案how do I handle enums without using
switch
orif
statements in C#?You don't. enums are just a pleasant syntax for writing
const int
.Consider this pattern:
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, }
And now you can say
public decimal Price { get { return PriceMethod.Invoke(this.PriceHistory); } }
And the user can say
myArticle.PriceMethod = PriceMethod.Max; decimal price = myArticle.Price;
这篇关于对于状态处理多态枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!