假设我想做一些自定义异常(exception)。我想拥有更多。我可以为每个新异常创建一个新类,但是还有另一种方法可以做到这一点吗?如果我必须始终创建一个新类,那么将它们存储在哪里?它只是在项目的根文件夹中看起来不太好。
嗯,还有另一个问题:如果某些异常是相同的,只是异常的名称发生了一点变化,我该怎么办?假设异常 A 看起来像这样:
[Serializable()]
public class ExceptionA: Exception, ISerializable
{
public ExceptionA() : base() { }
public ExceptionA(string message) : base(message) { }
public ExceptionA(string message, System.Exception inner) : base(message, inner) { }
public ExceptionA(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
另一个是一样的,只是另一个名字:
[Serializable()]
public class ExceptionB: Exception, ISerializable
{
public ExceptionB() : base() { }
public ExceptionB(string message) : base(message) { }
public ExceptionB(string message, System.Exception inner) : base(message, inner) { }
public ExceptionB(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
等等。我真的必须总是 创建一个新类并粘贴相同的代码吗?有什么建议吗?
最佳答案
I could create for every new exception a new class, but is there another way to do this?
不,没有别的办法。如果你想创建一个新的异常类型,你需要一个新的类。
where to store them?
在所有需要使用它们的代码都可以访问的位置。
what am I doing if some exceptions are the same, just the name of the exception is changing a little bit?
是的,仍然需要创建一个新类 - 尽管您可以从现有异常类派生新类。
关于c# - 在哪里/如何存储或处理大量自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12298598/