我们有一个自定义异常类,在我们的最后工作得很好(参见下面的代码1)。如果传入isVerified的参数为true,则需要使用此句子附加错误消息(“更改尚未提交”)。我对类进行了一些修改(参见code2),但看起来,我仍然会在抛出错误时得到原始消息。我非常感谢你的帮助。非常感谢。
代码1:
public class BusinessRuleValidationException : Exception
{
public BusinessRuleValidationException(string message):base(message)
{
}
}
码2:
public BusinessRuleValidationException(string message, bool isVerified)
: base(message)
{
if (isVerified)
message += " The change has not been committed.";
}
答案 0 :(得分:2)
问题是在修改消息之前调用Exception
基类的构造函数:
public BusinessRuleValidationException(string message, bool isVerified)
: base(message) // <- problem is here
{
if (isVerified)
message += " The change has not been committed.";
}
因此Message
属性已经设置,修改后的副本实际上从未分配给任何东西。正如Mark Larter指出的那样,你可以通过简单地改变你传递给构造函数的东西来解决这个问题:
public BusinessRuleValidationException(string message, bool isVerified)
: base(string.Format("{0}{1}", message, isVerified ? " The change has not been committed." : string.Empty))
{ }
答案 1 :(得分:0)
您可以试试这个,但我还没有测试过:
public BusinessRuleValidationException(string message, bool isVerified)
: base(isVerified ? (message += " The change has not been committed.") : message)
{ }