2015-10-16 78 views
1
我有我的代碼與此異常麻煩

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」)'... –

回答

1

有在處理這也是導致異常

0

嘗試第一加法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

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}(這是實際問題)

+0

t'm測試,我認爲我在我的格式中做了一個錯誤 – HDJEMAI

+0

它現在正在工作謝謝 – HDJEMAI

+0

很高興知道 – Kapoor