简体   繁体   English

WriteLine中的System.FormatException

[英]System.FormatException in WriteLine

I'm having a trouble in my code with this exception: 我在代码中遇到了这个异常的麻烦:

在此处输入图片说明

System.FormatException System.FormatException

Additional information: Input string was not in a correct format. 附加信息:输入字符串的格式不正确。

I have two files in my visual studio C# solution: 我的Visual Studio C#解决方案中有两个文件:

  1. Program.cs: 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. file Rectangle.cs : 文件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); } } } } 

The exception arise when I execute the line: rect.Length = 10; 当我执行以下行时出现异常: rect.Length = 10;

Please change the event handler like this, all will work fine 请像这样更改事件处理程序,一切正常

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

I have made 2 changes here - 我在这里做了2处更改-

  1. Added a string.Format (which is not the problem) 添加了string.Format(这不是问题)

  2. removed the space between { & 0 . 删除了{0之间的空格。 it was { 0} now I made it {0} (which is the actual problem) 现在是{ 0}现在是{0} (这是实际问题)

处理程序中{0之间有一个空格,这导致异常

Try first adding try catch to catch the error it is throwing. 首先尝试添加try catch来捕获它引发的错误。 So you could identify and fix it. 因此,您可以识别并修复它。 This is just to help you fix your own problem next time. 这只是为了帮助您下次解决自己的问题。 :) :)

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;
      }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM