gpt4 book ai didi

c# - Unity拦截概念清晰

转载 作者:太空狗 更新时间:2023-10-29 23:51:17 24 4
gpt4 key购买 nike

我正在关注 Unity Interception链接,在我的项目中实现 Unity。

通过链接,我创建了一个类,如下所示:

[AttributeUsage(AttributeTargets.Method)]
public class MyInterceptionAttribute : Attribute
{

}

public class MyLoggingCallHandler : ICallHandler
{
IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
IMethodReturn result = getNext()(input, getNext);
return result;
}
int ICallHandler.Order { get; set; }
}

public class AssemblyQualifiedTypeNameConverter : ConfigurationConverterBase
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (value != null)
{
Type typeValue = value as Type;
if (typeValue == null)
{
throw new ArgumentException("Cannot convert type", typeof(Type).Name);
}
if (typeValue != null) return (typeValue).AssemblyQualifiedName;
}
return null;
}

public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string stringValue = (string)value;
if (!string.IsNullOrEmpty(stringValue))
{
Type result = Type.GetType(stringValue, false);
if (result == null)
{
throw new ArgumentException("Invalid type", "value");
}
return result;
}
return null;
}
}

到目前为止,我没有做任何特别的事情,只是按照上面链接中解释的示例进行操作。但是,当我必须实现 Unity 拦截类时,我遇到了很多困惑。

假设,我必须在我的类中实现其中一种方法,例如:

[MyInterception]
public Model GetModelByID(Int32 ModelID)
{
return _business.GetModelByID(ModelID);
}

这是我被卡住的主要问题,我不知道如何在 GetModelByID() 方法上使用 Intercept 类以及如何获得统一性。

请帮帮我,也请解释一下Unity Interception的概念。

最佳答案

Unity拦截解释

拦截是一个概念,您可以在其中将“核心”代码与其他问题隔离开来。在你的方法中:

public Model GetModelByID(Int32 ModelID)
{
return _business.GetModelByID(ModelID);
}

您不想用其他代码“污染”它,例如日志记录、分析、缓存等,这不是该方法的核心概念的一部分,统一拦截将帮助您解决这个问题。

通过拦截,您可以在不接触实际代码的情况下向现有代码添加功能!

您的具体问题

if my _business is null then no call to GetModelById() should be made, how can I achieve that?

您实际上可以通过使用拦截和反射来实现您想要做的事情。我现在无法访问开发环境,但像这样的东西应该可以,

IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
IMethodReturn result = input.CreateMethodReturn(null, new object[0]);

var fieldInfos = input.Target.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
var businessField = fieldInfos.FirstOrDefault(f => f.Name == "_business");

if (businessField != null && businessField.GetValue(input.Target) != null)
result = getNext()(input, getNext);

return result;
}

您可以访问方法(您正在拦截的方法)所属的目标(对象),然后通过反射读取该对象私有(private)字段的值。

关于c# - Unity拦截概念清晰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21378233/

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