[英]System.FormatException in WriteLine
我在代碼中遇到了這個異常的麻煩:
System.FormatException
附加信息:輸入字符串的格式不正確。
我的Visual Studio C#解決方案中有兩個文件:
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); } } }
文件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;
請像這樣更改事件處理程序,一切正常
static void Rectangle_Changed(object sender, EventArgs e)
{
Rectangle rect = (Rectangle)sender;
Console.WriteLine(string.Format("Value Changed: Length = {0}", rect.Length));
}
我在這里做了2處更改-
添加了string.Format(這不是問題)
刪除了{
& 0
之間的空格。 現在是{ 0}
現在是{0}
(這是實際問題)
處理程序中{
和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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.