gpt4 book ai didi

c# - 操作可以泛化吗?

转载 作者:太空狗 更新时间:2023-10-29 19:40:00 25 4
gpt4 key购买 nike

我刚刚写了这段代码:

private double PerformOperation(OperationEnum operation, double aggregateValue, 
double sourceValue)
{
if (operation == OperationEnum.Sum)
return aggregateValue + sourceValue;
if (operation == OperationEnum.Subtract)
return aggregateValue - sourceValue;
if (operation == OperationEnum.Multiply)
return aggregateValue * sourceValue;
if (operation == OperationEnum.Divide)
return aggregateValue / sourceValue;
throw new InvalidOperationException("Unsupported Aggregation Operation");
}

看起来很重复。有没有办法概括这一点?所以我不必有 4 条相同的线,只是符号不同?

(注:如果有更好的不使用OperationEnum的方法就好了)

最佳答案

你可以制作一个Dictionary<OperationEnum, Func<double, double, double>> :

static readonly Dictionary<OperationEnum, Func<double, double, double>> operations = 
new Dictionary<OperationEnum, Func<double, double, double>> {
{ OperationEnum.Sum, (a, b) => a + b },
...
};

关于c# - 操作可以泛化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com