+ -
当前位置:首页 → 问答吧 → IContextAttribute特性 为什么会自动执行

IContextAttribute特性 为什么会自动执行

时间:2011-12-14

来源:互联网

C# code
User.CurrentUser = new User(name, tb_Psd.Text.Trim());

在执行这行代码时,User 类标注了特性:
C# code

[AspectOrientedAttribute]
class User{   }



AspectOrientedAttribute 特性继承自 IContextAttribute
C# code
public sealed class AspectOrientedAttribute : Attribute, IDisposable//, IContextAttribute



当我继承 IContextAttribute 时,AspectOrientedAttribute 会在 new User() 时执行自己的构造函数 和 IContextAttribute.IsContextOK 方法;

如果我取消了继承 IContextAttribute 时,在 new User() 时:AspectOrientedAttribute 却不会自己构造,更不会执行 IsContextOK 方法;



----------------------------------------------------------------------------------
换言之:当 User 的特性 是 IContextAttribute, 则特性将会自动构造执行;
否则却不会;

——凭什么 IContextAttribute 具有自动执行的权利??而其他特性就只能由我们人为的写 代码控制??

作者: sxl514286339   发布时间: 2011-12-14

看到了:原来是 User 继承了 : ContextBoundObject——是这个 父类在搞鬼

我是在研究一段AOP代码:刚才 构造 User 时,却先执行了 特性——这就是一种拦截机制的啦;
好了,精简源码也堪上来:



C# code

    class Program
    {
        static void Main(string[] args)
        {
            User user = new User();
            Console.WriteLine(user.GetType());
        }
    }

    public class MyAttribute : Attribute, IContextAttribute
    {
        public MyAttribute()
        {
            Console.WriteLine("特性 构造!");
        }

        public bool IsContextOK(Context ctx, IConstructionCallMessage msg)
        {
            Console.WriteLine("执行 IsContextOK!");
            return false;
        }
        public void GetPropertiesForNewContext(IConstructionCallMessage msg)
        {
            Console.WriteLine("执行 GetPropertiesForNewContext!");
        }
    }

    [MyAttribute]
    public class User : ContextBoundObject
    {
        public User()
        {
            Console.WriteLine("User 构造!");
        }
    }



执行结果 :


特性 构造!
执行 IsContextOK!
执行 GetPropertiesForNewContext!
User 构造!
IContextAttribute自动执行.User



作者: sxl514286339   发布时间: 2011-12-14

各位——结不了帖子;

送分啦!!!!!!

要分的来领取咧......

作者: sxl514286339   发布时间: 2011-12-14