How to plug method parameters into custom attribute

前端 未结 4 1087
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 08:13

I have a custom Attribute called AuthoriseAttribute whose constructor looks like this:

public AuthoriseAttribute(int userId)
{
  .. blah
}

This

4条回答
  •  既然无缘
    2021-02-19 09:09

    Making vcsjones' comment an answer, this is not possible.

    Attributes are metadata; they are compiled into the assembly at compile-time and do not change during runtime. As such, any parameters you pass into an attribute must be constants; literals, constant variables, compiler defines, etc.

    The one way this would work is to make the attribute an AOP element, using a framework like PostSharp or rolling your own with the Unity Framework etc. This would allow you to attach an "interceptor" to the method by decorating it with an attribute, which will then run code in the attribute and will also have knowledge about exactly how the method was called including parameter values. Check out this blog: http://www.progware.org/Blog/post/Interception-and-Interceptors-in-C-(Aspect-oriented-programming).aspx

提交回复
热议问题