System.FormatException 在 WriteLine 中

System.FormatException in WriteLine

我的代码遇到了这个异常问题:

System.FormatException

Additional information: Input string was not in a correct format.

我的 visual studio C# 解决方案中有两个文件:

  1. Program.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace EventPubSub
    {
        class Program
        {
            static void Main(string[] args)
            {
                Rectangle rect = new Rectangle();
                // Subscribe to the Changed event
                rect.Changed += new EventHandler(Rectangle_Changed);
                rect.Length = 10;
            }
            static void Rectangle_Changed(object sender, EventArgs e)
            {
                Rectangle rect = (Rectangle)sender;
                Console.WriteLine("Value Changed: Length = { 0}", rect.Length);
            }
        }
    }
    
  2. 文件Rectangle.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace EventPubSub
    {
        class Rectangle
        {
            //Declare an event named Changed of
            //delegate type EventHandler
    
            public event EventHandler Changed;
    
            private double length = 5;
    
            public double Length
            {
                get
                {
                    return length;
                }
                set
                {
                    length = value;
                    //Publish the Changed event
                    Changed(this, EventArgs.Empty);
                }
            }
        }
    }
    

执行以下行时出现异常:rect.Length = 10;

首先尝试添加 try catch 以捕获它抛出的错误。所以你可以识别并修复它。这只是为了帮助您下次解决自己的问题。 :)

static void Main(string[] args)
  {
     Rectangle rect = new Rectangle();
     string errorMessage = String.empty;
     try
     {
          // Subscribe to the Changed event
          rect.Changed += new EventHandler(Rectangle_Changed);
          rect.Length = 10;
      }
      catch(Exception ex)
      {
           errorMessage = ex.Message;
      }
  }

请像这样更改事件处理程序,一切都会正常工作

static void Rectangle_Changed(object sender, EventArgs e)
{
    Rectangle rect = (Rectangle)sender;
    Console.WriteLine(string.Format("Value Changed: Length = {0}", rect.Length));
}

我在这里做了 2 处更改 -

  1. 添加了一个string.Format(这不是问题)

  2. 删除了 {0 之间的 space。它是 { 0} 现在我做到了 {0} (这是实际问题)

在导致异常的处理程序中 {0 之间有一个 space