WriteLine中的System.FormatException

时间:2015-10-16 03:47:09

标签: c# console.writeline formatexception

我的代码遇到了这个例外的麻烦:

enter image description here

  

System.FormatException

     

其他信息:输入字符串的格式不正确。

我的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);
                }
            }
        }
    }
    
  3. 执行以下行时出现异常:rect.Length = 10;

3 个答案:

答案 0 :(得分:1)

请更改这样的事件处理程序,一切正常

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。它是{ 0}现在我做了{0}(这是实际问题)

答案 1 :(得分:1)

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

答案 2 :(得分:-1)

首先尝试添加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;
      }
  }