System.FormatException中的WriteLine

问题描述:

我有我的代码与此异常麻烦

System.FormatException中的WriteLine

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

的异常出现时我执行行:rect.Length = 10; 当我使用分步执行(F10

+1

极少数情况下'FormatException'不{0之间的空间由于'int.Parse(“bob”)'... –

有在处理这也是导致异常

尝试第一加法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; 
     } 
    } 
+0

这样做后,我有这样的消息:输入字符串不是在一个正确的格式。 – HDJEMAI

+0

那么它意味着你的问题在消息部分。我只是在这里教你如何处理下一次这种错误。 “教人如何钓鱼比喂鱼好。” ;) – bot

+0

是的,你是对的,再次感谢的 – HDJEMAI

请更改事件处理程序就是这样,一切都将正常工作

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}(这是实际问题)

+0

t'm测试,我认为我在我的格式中做了一个错误 – HDJEMAI

+0

它现在正在工作谢谢 – HDJEMAI

+0

很高兴知道 – Kapoor