【问题标题】:PostSharp Interface Method AttributePostSharp 接口方法属性
【发布时间】:2019-07-18 23:06:38
【问题描述】:

想象一下我有以下几点:

public interface IMyInterface {
    void DoSomething();
}

public class MyClass: IMyInterface {
    public void DoSomething() {
        // do something
    }
}

然后,我想像这样创建一个方法属性:

[PSerializable]
[AttributeUsage(AttributeTargets.Method)]
public class NotNullAttribute : MethodImplementationAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        throw new NullReferenceException();
    }
}

现在,我知道我可以将它应用到类方法中。

但是,我希望能够执行以下操作:

public interface IMyInterface {
    [NotNull]
    void DoSomething();
}

然后,所有实现此方法的类都应用了拦截器。不幸的是,这在编译时给了我一个错误。

这可能吗?我试图在文档中找到答案,但没有成功。

如果这可能的,有人可以帮我理解如何完成这个吗?

【问题讨论】:

    标签: c# c#-4.0 postsharp


    【解决方案1】:

    我搞定了……

    我在属性定义和抽象方法上都缺少一个属性。

    工作示例:

    [PSerializable]
    [MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Instance)]
    [AttributeUsage(AttributeTargets.Method)]
    public class NotNullAttribute : MethodInterceptionAspect
    {
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            throw new NullReferenceException();
        }
    }
    

    以及如何使用:

    public interface IMyInterface {
        [NotNull(AttributeInheritance = MulticastInheritance.Multicast)]
        void DoSomething();
    }
    
    public class MyClass: IMyInterface {
        public void DoSomething() {
            // do something
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多