无法使用'int'类型的值
问题描述:
我只学习C#,无法弄清楚这段代码有什么问题。无法使用'int'类型的值
错误CS1750型“INT”的值,因为没有标准转换到类型不能被用作默认参数“MidpointRounding”
代码:
public static double MyRound(double value, int point, MidpointRounding midpointRounding = 1)
{
if (!Enum.IsDefined(typeof (MidpointRounding), midpointRounding))
throw new ArgumentOutOfRangeException(nameof(midpointRounding));
decimal num = (decimal)((double)value);
try
{
num = Math.Round(num, point, midpointRounding);
}
catch (Exception exception1)
{
Exception exception = exception1;
MessageBox.Show(exception.Message, "Error : MyRound", MessageBoxButton.OK, MessageBoxImage.Hand);
}
return (double)((double)num);
}
答
最后参数类型为MidpointRounding
,这是一个枚举。您可以隐式分配给枚举的唯一int
字符是0
。您提供了默认值1
,这是编译器所抱怨的。
改为使用MidpointRounding.ToEven
,如果这就是你的意思。
其他一些意见:
- 没有必要检查是否
midpointRounding
在范围内,Math.Round
will take care of that。 - 不要显示异常消息框,这不是一个好方法,它将UI代码与逻辑代码混合在一起。如果有的话,你应该让异常传播。
- 你写
return (double)((double)num);
,一个投就足够了;) - 无需投
(double)value
,为value
已经是一个double
- 最后...铸造一
double
到decimal
,然后用给定的方法舍入,然后把它重新投回double
是不是一个好主意。你会失去精确度,而中点四舍五入方法很可能会被击败。如果中点舍入方法很重要,一直使用decimal
。
你在哪一行得到它? –
你有一个明确的错误消息,告诉你什么是有问题的语句/行。你期望这样做? – kai
@VisualVincent错误消息说它是函数声明(因为它说默认参数) – kai