【问题标题】:How to convert null to default(float) or 0如何将 null 转换为默认值(浮点数)或 0
【发布时间】:2017-02-19 20:23:01
【问题描述】:

我正在尝试获取浮点值作为输入,如果跳过一个值以将其设置为 0,但由于跳过将其设置为 null,我得到一个异常。所以,我尝试使用“??”像这样的操作员:

float speed = Convert.ToSingle(Console.ReadLine()) ?? default(float);

float speed = Convert.ToSingle(Console.ReadLine()) ?? 0;

但我得到一个错误:

错误 CS0019:操作员 '??'不能应用于类型的操作数 'float' 和 'int'

我将如何写这样的:float y = x ?? 0;

public static void CalculateDistanceTimeSpeed()
{
    Console.WriteLine("Find distance/speed/time based on any of the two.");
    Console.WriteLine("Enter two of the three requirements");
    Console.WriteLine();

    Console.WriteLine("Enter speed in km/h (Enter 0 if unkown)");
    float speed = Convert.ToSingle(Console.ReadLine());

    Console.WriteLine("Enter distance in km (Enter 0 if unkown)");
    float distance = Convert.ToSingle(Console.ReadLine());

    Console.WriteLine("Enter time in hour/s (Enter 0 if unkown)");
    float time = Convert.ToSingle(Console.ReadLine());

    Console.WriteLine(distance, speed, time);

    if (speed == 0)
    {
        speed = distance / time;
        speed.ToString("0.##");

        Console.WriteLine("Determined Average speed : {1}km/h, based on distance: {0}km and time: {2}hrs.", distance, speed, time);
    }

    else if (distance == 0)
    {
        distance = time / speed;
        distance.ToString("0.##");

        Console.WriteLine("Determined distance traveled : {0}km, based on speed: {1}km/h and time: {2}hrs.", distance, speed, time);

    }

    else
    {
        time = distance / speed;
        time.ToString("0.##");

        Console.WriteLine("Determined time traveled: {2}hrs, based on speed: {1}km/h for distance: {0}km.", distance, speed, time);
    } 

【问题讨论】:

  • 我在这里看不到null
  • 使用 float.TryParse.
  • 先搜索一下为什么会出现这个错误?因为数据类型不可为空。所以你可以检查如何使它可以为空。

标签: c#


【解决方案1】:

Convert.ToSingle() 如果格式未知,将抛出异常,它永远不会返回 null。您应该使用Single.TryParse() 轻松检查结果是否正确。

float speed;
if (!Single.TryParse(Console.ReadLine(), out speed))
    speed = 0f;

另请注意,这些方法将使用当前语言环境,因此它们可能会在不同语言环境中接受不同的输入。如果需要使用特定语言环境(例如小数分隔符)进行输入,请确保指定正确的语言环境

【讨论】:

    【解决方案2】:

    只是为了回答你的问题:

    我将如何写这个等价物:float y = x ?? 0

    float? x = 10f;
    float y = x ?? 0f;
    

    【讨论】:

      【解决方案3】:

      您需要使用0f 告诉编译器您的0 是float 而不是int

      详情请见MSDN

      【讨论】:

      • 但是他不能对值类型使用空合并运算符,只能对可以为空的类型(引用类型)使用。
      • 他的问题是“我将如何写出这样的等价物:float y = x ?? 0;”
      【解决方案4】:

      您不能将 null 合并运算符用于值类型(nullable types 除外),只能用于可以是 null 的引用类型。但是,您可以使用这种单线:

      float speed =  Single.TryParse(Console.ReadLine(), out speed) ? speed : default(float);
      

      【讨论】:

      • 这不是真的,您可以将空合并运算符与可空类型一起使用,这些类型也是值类型。
      【解决方案5】:

      你不能。 由于Convert.ToSingle() 返回float 而不是float?,因此结果永远不会是null

      【讨论】:

        【解决方案6】:

        已经发布了有效的答案,但我想给出一些背景为什么会出现这个错误error CS0019: Operator ??' cannot be applied to operands of type 'float' and 'int' 是合适的。

        在 C# 中,我们有引用类型和值类型。区别是

        引用类型的变量存储对其数据(对象)的引用,而值类型的变量直接包含其数据。

        MSDN 中所述。

        由于floatinta couple more 类型实际上是值类型,因此很明显为什么不能将null-coalescing operator 用于这些类型。它们根本不可能是null,因为它们不存储任何引用(可能是null),而是值本身。

        【讨论】:

          【解决方案7】:

          那行得通。多谢你们。这是对我有用的解决方案,以防有人好奇。

          public static void CalculateDistanceTimeSpeed()
          {
              float speed;
              float distance;
              float time;
          
              Console.WriteLine("Find distance/speed/time based on any of the two.");
              Console.WriteLine("Enter two of the three requirements");
              Console.WriteLine();
          
              Console.WriteLine("Enter speed in km/h");
              if (!Single.TryParse(Console.ReadLine(), out speed))
                  speed = 0f;
          
              Console.WriteLine("Enter distance in km");
              if (!Single.TryParse(Console.ReadLine(), out distance))
                  distance = 0f;
          
              Console.WriteLine("Enter time in hour/s");
              if (!Single.TryParse(Console.ReadLine(), out time))
                  time = 0f;
          
              if (speed == 0f)
              {
                  speed = distance / time;
                  Console.WriteLine("Required average Speed : {1}km/h for distance {0}km and time {2}hrs.", distance, speed.ToString("0.##"), time);
              }
          
              else if (distance == 0f)
              {
                  distance = speed * time;
                  Console.WriteLine("Distance traveled : {0}km at speed {1}km/h for {2}hrs.", distance.ToString("0.##"), speed, time);
          
              }
          
              else
              {
                  time = distance / speed;
                  Console.WriteLine("Travel time: {2}hrs with speed {1}km/h for distance {0}km.", distance, speed, time.ToString("0.##"));
              } 
          
              // add mph conversion
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-09-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-09
            • 2017-11-01
            相关资源
            最近更新 更多