System.FormatException中的WriteLine
问题描述:
我有我的代码与此异常麻烦
:System.FormatException中的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;
当我使用分步执行(F10
)
答
有在处理这也是导致异常
答
尝试第一加法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;
}
}
答
请更改事件处理程序就是这样,一切都将正常工作
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}
(这是实际问题)
极少数情况下'FormatException'不
{
和0
之间的空间由于'int.Parse(“bob”)'... –