【发布时间】:2011-08-18 20:45:04
【问题描述】:
我想要一个扩展方法或通用方法,即使有一些异常,我也希望代码继续执行,并继续在列表中记录异常。这是我尝试过的一个例子
public void ValidateName()
{
if (_customer.Name.Length < 5)
throw new Exception("shortname");
}
public void ValidateAge()
{
if (_customer.Age < 5)
throw new Exception("short age");
}
internal void Validate()
{
this.CatchAndContinue(delegate()
{
this.ValidateName(); // throws exception and add to list
this.ValidateAge(); // but this should also execute
});
}
public void CatchAndContinue(Action action)
{
try
{
action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
对于当前类,我可以将异常传递给 ValidateName 和 ValidateAge 方法,但我希望我们可以按照我想要的方式进行,而 validate() 方法主体几乎没有变化。我知道从语义上讲这听起来很奇怪,但我需要很多地方来做到这一点。或者如果有更好的方法来实现它
编辑
这个验证是一个简单的例子,并不是在所有场景中它都只是验证器。顺便说一句,在这种情况下,我想向 UI 提供错误列表以及为什么抛出,因为当从 DB 构造模型时(由于 DB 中的数据错误),不应创建此类对象。这些只是关注的例子
【问题讨论】:
标签: c#