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/