简单的例子。

it2022-05-09  24

自定义Attribute 自定义Attribute  1using System; 2 3namespace Relaction.test1 4{ 5    /**//// <summary> 6    /// 自定义的Attribute类型。 7    /// </summary> 8    ///  9    [AttributeUsage(AttributeTargets.Class,Inherited=false,AllowMultiple=false)]10    public class ClassShowProcessAttribute:Attribute11    {12        private bool _show = false;13        public bool Show14        {15            get16            {17                return _show;18            }19        }20        public ClassShowProcessAttribute(bool show)21        {22            _show = show;23        }24    }25} 使用上面的Attribute。 使用Attribute  1using System; 2 3namespace Relaction.test1 4{ 5    /**//// <summary> 6    /// 给这个类贴上自定义的属性。 7    /// </summary> 8    ///  9    [ClassShowProcess(false)]10    public class AttrClassTest11    {12        public AttrClassTest()13        {}14    }15}16 应用测试: 应用测试  1    private void button2_Click(object sender, System.EventArgs e) 2        { 3            object[] o = new object[]{new AttrClassTest(),new AttrClassTest(),"TEST"}; 4            foreach(object item in o) 5            { 6                ClassShowProcessAttribute[] attr = (ClassShowProcessAttribute[])item.GetType().GetCustomAttributes(typeof(ClassShowProcessAttribute),false); 7                if(attr.Length != 0) 8                { 9                    if(attr[0].Show)10                    {11                        label1.Text += item.ToString();12                    }13                }14            }15        }

转载于:https://www.cnblogs.com/nanshouyong326/archive/2006/11/27/573482.html


最新回复(0)