gpt4 book ai didi

c# - 如何通过 IInterceptionBehavior 吞下异常?

转载 作者:太空狗 更新时间:2023-10-30 01:24:57 25 4
gpt4 key购买 nike

我有一个类似打击的 IInterceptionBehavior:

public class TraceBehavior : IInterceptionBehavior
{
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}

public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
Console.WriteLine(string.Format("Invoke method:{0}",input.MethodBase.ToString()));
IMethodReturn result = getNext()(input, getNext);
if (result.Exception == null)
{
Console.WriteLine("Invoke successful!");
}
else
{
Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
result.Exception = null;
}
return result;
}

public bool WillExecute { get { return true; } }
}

无论我是否将其放在方法上,总是会抛出异常。谁能帮帮我?

最佳答案

代码看起来不错,但您没有说明如何注册拦截以及如何调用对象。

假设正在调用拦截,那么如果我猜测调用的方法将返回一个值类型并且 IMethodReturn.ReturnValue 为 null,这将导致 NullReferenceException.

如果是这种情况,那么返回值类型的默认值可能会解决您的问题:

public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
Console.WriteLine(string.Format("Invoke method:{0}", input.MethodBase.ToString()));
IMethodReturn result = getNext()(input, getNext);
if (result.Exception == null)
{
Console.WriteLine("Invoke successful!");
}
else
{
Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
result.Exception = null;

Type type = ((MethodInfo)input.MethodBase).ReturnType;

if (type.IsValueType)
{
result.ReturnValue = Activator.CreateInstance(type);
}
}
return result;
}

关于c# - 如何通过 IInterceptionBehavior 吞下异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8036559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com