有没有一种方法可以为带有属性的Class标记,从而为所有方法添加属性?
例如:
[TestAspect]
public class Test
{
public void foo() { ... };
[AttributeA]
public void bar() { ... };
}
现在,TestAspect应该做到了,将Aspects添加到bar()。
我已经编写了一个AspectProvider
类,以下内容应将AspectA和AspectB应用于该类的所有具有AttributeA的方法。
[Serializable, AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class TestAspect : TypeLevelAspect, IAspectProvider
{
private static readonly CustomAttributeIntroductionAspect aspectA =
new CustomAttributeIntroductionAspect(
new ObjectConstruction(typeof(AspectB).GetConstructor(Type.EmptyTypes)));
private static readonly CustomAttributeIntroductionAspect aspectB =
new CustomAttributeIntroductionAspect(
new ObjectConstruction(typeof(AspectA).GetConstructor(Type.EmptyTypes)));
public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
{
Type targetClassType = (Type)targetElement;
foreach(MethodInfo methodInfo in targetClassType.GetMethods())
{
if(!methodInfo.IsDefined(typeof(AttributeA), false))
{
yield break;
}
yield return new AspectInstance(targetElement, aspectA);
yield return new AspectInstance(targetElement, aspectB);
}
}
但是不幸的是,属性没有应用于方法吗?没有引发异常或错误。
有人建议吗?
答案 0 :(得分:1)
使用以下代码,我至少可以向类中用AttributeA
标记为TestClass
的方法中添加1个自定义属性。
[Serializable, AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class TestClassAttribute : TypeLevelAspect, IAspectProvider
{
public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
{
Type type = (Type)targetElement;
return type.GetMethods().Where(method => method.GetCustomAttributes(typeof(AttributeA), false)
.Any()).Select(m => new AspectInstance(m, new CustomAttributeIntroductionAspect(
new ObjectConstruction(typeof(AttributeB).GetConstructor(Type.EmptyTypes)))));
}
}