我需要一个建议,拜托。情况如下:
我有一个图书馆,用来操作一些硬件。机器的一个参数是Quant (一个包中应该有多少个产品)。它可分为三种类型:
*quant type | value type*
Weight | double
Pieces | Integer
Without | null我可以创建一个存储Quant值的结构,例如:
public struct Quant
{
public QuantTypes QuantType { get; set; }
public double QuantWeightValue { get; set; }
public int QuantPieceValue { get; set; }
...
}但是在工作过程中,我需要多次检查量化的状态和值。这变得很困难,因为我需要依靠quantType获得价值
if(QuantType == QuantTypes.Piece)
{
if(QuantWeightValue > 5)
QuantWeightValue += 2.5;
}
else
{
if(QuantPieceValue > 5)
QuantPieceValue += 2;
}
SetNewQuantToMachine();我不喜欢它。我只能为双类型的量化值创建一个字段。但这样就有可能用非整数值来设置块类型的量化。在这种情况下,我看到两个解决方案:
也许有人会给我一个建议,什么是最好的做法来写这样的代码。也许GenericTypes在这种情况下是合适的?
发布于 2017-05-18 13:43:27
为Quant的每个子类型创建单独的类。提供一个采用IQuant接口的方法,并使用dynamic向特定类型的覆盖调度。
interface IQuant {
QuantTypes QuantType { get; }
}
class QuantWeight {
public QuantTypes QuantType {
get { return QuantTypes.Weight; }
}
public double QuantWeightValue { get; }
}
class QuantCount {
public QuantTypes QuantType {
get { return QuantTypes.Pieces; }
}
public int PiecesValue { get; }
}您的公共方法如下所示:
public void ProcessQuant(IQuant quant) {
ProcessQuantImpl((dynamic)quant);
}
private void ProcessQuantImpl(QuantWeight weight) {
... // Do the real work here
}
private void ProcessQuantImpl(QuantCount pieces) {
... // Do the real work here
}发布于 2017-05-18 13:43:45
如果我搞错了很抱歉。但我可以建议将"Quant“改为类安装基版本,然后使用不同的变量创建继承的类数,然后只使用"quant.GetValue()”之类的内容。说得通吗?
https://stackoverflow.com/questions/44049235
复制相似问题