C# Question.任意类Class
有方法Foo()
,一个可以抛出异常的方法。 有没有办法bar()
Class
添加一个私有回调机制,这样如果Foo()
抛出异常,bar()
执行将在抛出继续向上链之前触发?如果这不能发生,那么在捕获异常后呢?
--编辑--
由于一些最初的评论是"这令人困惑,你在做什么,伙计",我将进一步解决它。
我想要异常侦听器的原因是因为我有一些关于类Class
的可公开可读的布尔状态,每当抛出异常时,我都希望将其设置为 true。由于Class
中可能有多个函数会引发异常,因此我不想在每次抛出异常时都将 hasError 设置为 true 的样板工作。 自动化,宝贝。
所以我们的界面和主要功能是:
public interface IObjectProvider
{
IEnumerable<object> Allobjects { get; }
}
public interface IContext
{
delegate bool ContextIsStillValid(object o);
delegate void Run(object o);
}
// main program
public static void Main() {
IContext context = initcontext(...);
IObjectProvider objectProvider = initobjectprovider(...);
// ...program executes for awhile...
foreach(var obj in objectProvider.AllObjects)
{
if(context.ContextIsStillValid(obj))
{
try
{
context.Run(obj);
}
catch(Exception e)
{
// log the error
}
}
}
}
在上面的代码片段中,我们指定了一些将使用某些object
"运行"的IContext
,当且仅当该IContext
首先使用相同的object
成功通过"验证"检查时。 好。 现在,IContext
实现的常见变体如下(相信我的话,它是(:
public class Class : IContext {
private bool _hasError = false;
// so our validation check is implemented with an internal flag.
// how is it set?
public bool ContextIsStillValid = (o) => !_hasError;
public void Run =
(o) =>
{
string potentially_null_string = getstring(...);
if(potentially_null_string == null)
{
// our internal flag is set upon the need to throw an exception
this._hasError = true;
throw new Exception("string was null at wrong time");
}
Global.DoSomethingWith(potentially_null_string.Split(',');
};
}
在这里,我们演示了一个常见的IContext
实现,这样一旦Run
方法抛出一个Exception
,Run
方法应该变得无法访问,因为随后IsContextStillValid
总是返回false。
现在想象一下,在我们的Run(object)
实现中还有其他抛出异常的调用。问题是,每次我们要抛出新的异常时,我们都必须复制代码以达到_hasError = true; throw new Exception(...);
的效果。 理想情况下,异常侦听器将为我们解决此问题,我很好奇你们中是否有人知道如何实现一个。
希望有帮助。
public class MyClass
{
public void Foo()
{
try
{
//Execute some code that might fail
}
catch
{
bar();
throw;
}
}
private void bar()
{
//do something before throwing
}
}