【问题标题】:A value of type 'int' cannot be used不能使用“int”类型的值
【发布时间】:2016-07-23 05:09:17
【问题描述】:

我只是学习 C#,无法弄清楚这段代码有什么问题。

错误 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);
}

【问题讨论】:

  • 你在哪一行得到它?
  • 你有一个明确的错误信息告诉你有问题的语句/行是什么。你希望这会做什么?
  • @VisualVincent 错误消息说它是函数声明(因为它说的是默认参数)
  • @kai :好吧,我不是 C# 开发人员,所以……但很高兴知道。 :)

标签: c#


【解决方案1】:

最后一个参数的类型是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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多