C#异常处理(给定一个构造一个字符串) [英] C# exception handling (with a string given to a constructor)
问题描述
我有一个有一个的ToString类WeekdayException()。
我想返回字符串中构造成立(非法平日:+ wday)用的ToString()。 ?如何访问字符串
使用系统;
类WeekdayException:ApplicationException的{
公共WeekdayException(字符串wday):基地(非法平日:+ wday){}
公共重写字符串的ToString()
{
返回HELLO+ ???;
}
}
类TryCatchFinally
{
公共静态无效的主要(字串[] args)
{
试
{
抛出新WeekdayException(通过试抛出);
}
赶上(ApplicationException的前)
{
Console.WriteLine(抓......+ ex.ToString());
}
}
}
和是这样的(制作和使用的ToString())的是C#程序员使用的方法?如果不是,有什么去了?
这是如何访问 wday $的方式C $ C>特别加入了
私人
成员变量(见下文):
类WeekdayException:ApplicationException的{
私人只读字符串工作日;
公共WeekdayException(字符串wday):基地(非法平日:+ wday){
this.weekday = wday;
}
公共重写字符串的ToString()
{
返回HELLO+ this.weekday;
}
}
和这是(制作和使用
的ToString()
)的C#程序员使用的方法?如果不是,有什么去了?
块引用>
为您设置并使用
消息异常通常$的方式C $ C>属性,当你调用构造函数的基
ApplicationException的
这是设置。类WeekdayException:ApplicationException的{
公共WeekdayException(字符串工作日)
:基地(非法平日:+工作日){}
}
然后:
尝试{
抛出新WeekdayException(星期二);
}
赶上(WeekdayException weekdayException){
Console.WriteLine(weekdayException.Message);
}
最后,不要像缩写
名平日
更短的变种,比如wday
。只需使用全名。I have a WeekdayException class that has the ToString(). I want to return the string set up in Constructor ("Illegal weekday: " + wday) with ToString(). How to access the string?
using System; class WeekdayException : ApplicationException { public WeekdayException(String wday) : base("Illegal weekday: " + wday) {} public override string ToString() { return "HELLO" + ???; } } class TryCatchFinally { public static void Main(String[] args) { try { throw new WeekdayException("thrown by try"); } catch (ApplicationException ex) { Console.WriteLine("Catch ..." + ex.ToString()); } } }
And is this (making and using ToString()) the method that C# programmers use? If not, what's the way to go?
解决方案This is how you can access
wday
specifically by adding aprivate
member variable (but see below):class WeekdayException : ApplicationException { private readonly string weekday; public WeekdayException(String wday) : base("Illegal weekday: " + wday) { this.weekday = wday; } public override string ToString() { return "HELLO " + this.weekday; } }
And is this (making and using
ToString()
) the method that C# programmers use? If not, what's the way to go?Typically for exceptions you set and use the
Message
property which is set when you invoke the constructor for the baseApplicationException
.class WeekdayException : ApplicationException { public WeekdayException(string weekday) : base("Illegal weekday: " + weekday) { } }
Then:
try { throw new WeekdayException("Tuesday"); } catch(WeekdayException weekdayException) { Console.WriteLine(weekdayException.Message); }
Finally, don't abbreviate names like
weekday
to shorter variants likewday
. Just use the full name.这篇关于C#异常处理(给定一个构造一个字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!