c# - 如何将方面应用于特定元素(例如,对于 LocationInfo 类型参数或 PropertyInfo)?

标签 c# aop postsharp

TL/DR:

如何将 Aspect 应用于特定元素,例如对于 LocationInfo 类型参数,或 PropertyInfo

详细说明:

我想在RuntimeInitialize期间找到属性/字段的所有依赖项

[Serializable]
public class NotifyPropertyChangedAspect : LocationInterceptionAspect {
    /* ... stuff ... */
    public override void RuntimeInitialize(LocationInfo locationInfo)
    {
        foreach(var attr in locationInfo.PropertyInfo.GetCustomAttributes(false)
                                .OfType<DependsOnAttribute>();){
            this.SaveDependencies(attr.Dependencies);
        }
        base.RuntimeInitialize(locationInfo);
    }
    /* ... things ... */
}

上面的代码适用于属性:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class DependsOnAttribute : Attribute {
    public string[] Dependencies { get; set; }
    public DependsOnAttribute(params string[] dependencies) { Dependencies = dependencies; }
}

[NotifyPropertyChangedAspect]
class MyClass {
    public string Name { get; set; }
    [DependsOnAttribute("Name")]
    public bool IsChanged { get; set; }
}

但不适用于方面:

[Serializable]
public class DependsOnAspect : LocationLevelAspect {
    public string[] Dependencies { get; set; }
    public DependsOnAspect(params string[] dependencies) { Dependencies = dependencies; }
}

[NotifyPropertyChangedAspect]
class MyClass {
    public string Name { get; set; }
    [DependsOnAspect("Name")]
    public bool IsChanged { get; set; }
}

最佳答案

方面是多播属性的特例。简而言之,在 PostSharp 处理程序集后,多播属性将从程序集中删除。要覆盖此行为,您需要指定以下内容:

[MulticastAttributeUsage(PersistMetaData = true)]
public class DependsOnAspect : LocationLevelAspect { ... }

这将告诉 PostSharp 您需要在运行时提供方面属性。

关于c# - 如何将方面应用于特定元素(例如,对于 LocationInfo 类型参数或 PropertyInfo)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26460274/

相关文章:

c# - 替换方法的 MethodBody 中的指令

c# - 检测明亮和黑暗的图像

c# - 在 UserControls( View )MVVM Prism 之间传递 ModelData(上下文)

c# - .NET WinForms 中 UI 元素的授权

java - AspectJ 示例项目中出现错误

c# - 如何使用 OnException 方面(PostSharp)继续方法流程?

c# - IEnumerable<T >'requires ' 1' 类型参数

c# - 隐藏 DockPanel 中的元素并调整大小

java - 使用 AspectJ 获取对象实例化并访问其相关属性和方法

c# - Postsharp:它是如何工作的?