所以我在.NET中使用属性玩了一些,并意识到每次调用Type.GetCustomAttributes()都会创建一个属性的新实例.这是为什么?我认为属性实例基本上是一个single-each-MemberInfo,1个实例绑定到Type,PropertyInfo等...
这是我的测试代码:
using System;
namespace AttribTest
{
[AttributeUsage(AttributeTargets.Class)]
class MyAttribAttribute : Attribute
{
public string Value { get; set; }
public MyAttribAttribute()
: base()
{
Console.WriteLine("Created MyAttrib instance");
}
}
[MyAttrib(Value = "SetOnClass")]
class MyClass
{
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Getting attributes for MyClass.");
object[] a = typeof(MyClass).GetCustomAttributes(false);
((MyAttribAttribute)a[0]).Value = "a1";
Console.WriteLine("Getting attributes for MyClass.");
a = typeof(MyClass).GetCustomAttributes(false);
Console.WriteLine(((MyAttribAttribute)a[0]).Value);
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我要实现属性,我希望输出为:
Created MyAttrib instance
Getting attributes for MyClass.
Getting attributes …Run Code Online (Sandbox Code Playgroud) 我只想知道AuthorizeAttribute的生命周期,并开始调试AuthorizeAttribute的默认构造函数,但无法获得任何命中.
这是自定义授权过滤器的代码.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public CustomAuthorizeAttribute() : base()
{
string test = string.Empty;
}
public override void OnAuthorization(HttpActionContext actionContext)
{
//Some code
}
}
Run Code Online (Sandbox Code Playgroud)
有人请帮我理解这个AuthorizeAttribute的生命周期吗?
谢谢