日期:2014-05-17  浏览次数:20735 次

用特性怎么标记属性
我想用特性标记属性,这个属性的特性等于某个值时执行一个操作,求用法

------解决方案--------------------
做法感觉挺奇葩,感兴趣我写了一下,没写完下班了,你可以自己改一下

 class TestAttributes
    {
        private string test;

        [MyAttribute(My="变量信息")]
        public string Test
        {
            get { return test; }
            set { test = value; }
        }
    }

    [AttributeUsage(AttributeTargets.All)]
    public class MyAttribute : Attribute
    {
        private string my;
        /// <summary>
        /// 实体实际对应的表名
        /// </summary>
        public string My
        {
            get { return my; }
            set { my = value; }
        }
    }

调用代码,目前只写到遍历特性名称,肚子饿了,啃饭去,明天有空的话再接着写

Type tAb = typeof(TestAttributes);
            foreach (System.Reflection.PropertyInfo propInfo in tAb.GetProperties())
            {
                MessageBox.Show(propInfo.Name);
                object[] testAb = propInfo.GetCustomAttributes(typeof(MyAttribute), true);
                foreach (object cAb in testAb)
                {
                    MessageBox.Show(cAb.ToString());
                }
            }