C# Attributes 笔记

Attribute

Attribute是给compiler看的,compiler会给提示信息。

特性对象是类的(或者属性的,方法的),不是对象的,类似static成员。

通过对象获取不到attribute对象,必须通过Type。

Obsolete特性示例

    class Person {
        //给方法加attributes, Obsolete实际上是ObsoleteAttribute类,这里也可以写成[ObsoleteAttribute]
        [Obsolete]
        public void SayHi() {
            Console.WriteLine();
        }

        [Obsolete("obsolete method, please use NewSayHi2")]
        public void NewSayHi1() { 
        
        }

        public void NewSayHi2()
        {

        }
    }

    [Obsolete("obsolete class")]
    class Dog { 
    }
   class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.SayHi();
            p.NewSayHi1();
            p.NewSayHi2();
            Dog d = new Dog();
            Console.ReadLine();
        }
    }
编译的时候,会给警告提示。

特性的本质:看il代码,实际上是在方法或者类中中创建了一个ObsoleteAttribute类的实例。VS根据判断类或者方法,属性中是否有attribute类的实例,如果有根据Attribute类的Message属性来得到提示消息。



自定义特性类

    [Message]
    class Animal { 
    }

    [Name]
    [Obsolete]
    class Cat : Animal { 
    
    }

    class NameAttribute : Attribute {
        private String name;
        public NameAttribute() { }
        public NameAttribute(String name) {
            this.name = name;
        }
        public String Name {
            get { return name; }
        }
    }

    class MessageAttribute : Attribute
    {

    }

不能给一个类(或方法,属性)贴多个 同一个特性。

    [Name]
    [Obsolete]
    class Cat { 
    
    }
        static void GetCustomAtrributesTest() {
            Cat cat1 = new Cat();
            Cat cat2 = new Cat();
            Type tCat = cat1.GetType();
            //得到所有这个类的attributes对象,包括继承来的
            IEnumerable<Attribute> attrs = tCat.GetCustomAttributes();
            //得到这个类的所有attributes对象,不包括继承来的
            object[] attrs1 = tCat.GetCustomAttributes(false);
            //得到某一个attribute对象
            Attribute nameAttributeObj = tCat.GetCustomAttribute(typeof(NameAttribute), false);
        }

看ButtonBase的源码,VS通过这些attributes显示 属性窗口中的各种信息


用特性方法显示记事本程序插件的名字

在MyNoteBookPlugInterfaceProject项目中加一个类:

namespace MyNoteBookPlugInterfaceProject
{
    public class PlugInNameAttribute : Attribute
    {
        private String name;
        public PlugInNameAttribute(String name)
        {
            this.name = name;
        }
        public String Name {
            get { return name; }
        }
    }
}
在NoteBookPlugIn项目中:
namespace NoteBookPlugIn
{
    [PlugInName("转换成大写")]
    public class PlugToUpper : MyNoteBookPlugInterfaceProject.IPlugIn
    {

        public string ProcessText(string text)
        {
            return text.ToUpper();
        }
    }
}
namespace NoteBookPlugIn
{
    [PlugInName("转换成小写")]
    public class PlugToLower : IPlugIn
    {
        public string ProcessText(string text)
        {
            return text.ToLower();
        }
    }
}

把新的NoteBookPlugIn.dll copy到MyNoteBookProject\bin\Debug\plugs目录下。

在记事本项目中,用attribute给menuitem的Header赋值
                        Attribute attr = t.GetCustomAttribute(typeof(PlugInNameAttribute), false);
                        MenuItem item = new MenuItem { Header = ((PlugInNameAttribute)(attr)).Name };

正则表达式校验Attribute : 一个通用的校验方法


1. 写RegexAttribute类

    class RegexAttribute : Attribute
    {
        String pattern;
        public RegexAttribute(String pattern)
        {
            this.pattern = pattern;
        }
        public bool IsMatch(String str){
            Console.WriteLine(str);
            if(str == null){
                return false;
            }
            return Regex.IsMatch(str, pattern);
        }
    }
2. 写验证方法,验证一个对象内有RegexAttribute特性的属性。 检查属性的值是否符合属性的规则(定义在属性的特性中)
    static class RegexUtil {
        public static bool CheckObjProperties(object obj) {
            bool ret = true;
            Type tObj = obj.GetType();
            PropertyInfo[] props = tObj.GetProperties(BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
            foreach (var p in props)
            {
                RegexAttribute regAttr = p.GetCustomAttribute(typeof(RegexAttribute), false) as RegexAttribute;
                if (regAttr != null)
                {
                    String strValue = p.GetValue(obj).ToString();
                    //Console.WriteLine(strValue);
                    if (!regAttr.IsMatch(strValue)) {
                        ret = false;
                        break;
                    }
                }
            }
            return ret;
        }
    }
3. 写一个类,在给属性加RegexAttribute特性
    class Bird {
        [RegexAttribute(@"\w{3,}")]
        public String Name { get; set; }
        [RegexAttribute(@"^\d{1,2}$")]
        public int Age { get; set; }
    }
4. 测试方法
        static void RegexAttributeTest() {
            Bird bird = new Bird { Name = "ast", Age=55555};
            if (RegexUtil.CheckObjProperties(bird))
            {
                Console.WriteLine("ok");
            }
            else {
                Console.WriteLine("not oK");
            }
        }


C#正则表达式小结

http://www.cnblogs.com/tempmen/archive/2010/07/20/1781576.html




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中,你可以为类、方法、属性或其他程序实体添加属性(Attributes)。属性是一种元数据,可以提供关于程序实体的额外信息,并可以在运行时通过反射来访问。要为一个程序实体添加属性,你需要使用方括号 [] 将属性放在目标实体的上方。 以下是一个简单的示例,展示如何在 C# 中添加属性: ```csharp using System; // 自定义属性类 public class MyAttribute : Attribute { public string Description { get; set; } public MyAttribute(string description) { Description = description; } } // 使用自定义属性 [MyAttribute("这是一个示例类")] public class MyClass { [MyAttribute("这是一个示例方法")] public void MyMethod() { // 方法的实现 } } class Program { static void Main(string[] args) { // 获取类上的属性 var classAttribute = (MyAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(MyAttribute)); Console.WriteLine(classAttribute.Description); // 获取方法上的属性 var methodInfo = typeof(MyClass).GetMethod("MyMethod"); var methodAttribute = (MyAttribute)Attribute.GetCustomAttribute(methodInfo, typeof(MyAttribute)); Console.WriteLine(methodAttribute.Description); } } ``` 在上述示例中,我们定义了一个名为 `MyAttribute` 的自定义属性类。然后,我们将 `MyAttribute` 属性应用于 `MyClass` 类和其中的 `MyMethod` 方法。在 `Main` 方法中,我们使用反射来获取并打印这些属性的描述信息。 请注意,属性可以具有不同的参数和返回类型,这取决于你的需求。你可以根据自己的需要定义和使用属性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值