本文介绍了需要用于控制默认Exception.ToString()的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
namespace ConsoleApplication6
{
using System;
class Program
{
static void Main(string[] args)
{
var ex = new Exception("Outer", new MyException("Inner"));
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
public class MyException : Exception
{
public MyException(string message)
: base(message)
{}
public override string ToString()
{
return "Nothing here to see";
}
}
}
推荐答案
如我所见,您有两个选择:
As I see it you have two options:
- 仅抛出并捕获 MyException 并使用其ToString().
- 为Exception类创建扩展,该扩展检查内部异常以及其类型是否为 MyException 它会根据需要简单地获取ToString或消息.然后,当它被捕获时,调用扩展而不是ToString.
- Only throw and catch the MyException and use its ToString().
- Create an extension for the Exception class which checks the inner exception and if its type is theMyException it simpy gets its ToString or message as needed. Then when it is caught call the extension instead of ToString.
HTH
这篇关于需要用于控制默认Exception.ToString()的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!