C#attribute

今天我来总结attribute,只是入门级的皮毛,大神请回避。

定义:

MADN的定义为:公共语言运行时允许添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型、字段、方法和属性等。Attributes和Microsoft .NET Framework文件的元数据(metadata)保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为。

我们简单的总结为:目标元素的关联附加信息

作用:

通过添加attribute,可以对函数和类添加一些属性信息,所以可以对使用权限等做一些限值,比如只允许调试的时候运行( Attribute:Conditional 和 Obsolete(废弃的函数)),或者防止跨域攻击,属性限制等。

    //Debug只在debug状态下会输出,Trace在Release下会输出
        [Conditional("DEBUG")]
        static void function1()
        {
            Console.WriteLine("这个函数被标记了debug");
        }
        //后面可以没有参数,默认也可以使用,标记true后就不能编译并且报错
        [Obsolete("已经被废弃",true)]
        static void function2()
        {
            Console.WriteLine("这是一个被废弃的函数");
        }    

使用:

可以使用默认,或者自定义。默认的使用方法如上。

自定义步骤如下:

1、新建类,本质就是一个类。

  //可以设置使用范围,是否可以为一个程序元素设置多次这个属性,设置属性是否可以被继承等。
[AttributeUsage(AttributeTargets.Class,AllowMultiple = true,Inherited = false)] public class HelpAttribute:Attribute { protected string description; public HelpAttribute(string str) { description = str; } public string Description { get { return description; } } }

2、使用

  [Help("这是我自己创建的属性")]
    public class AnyClass
    {
        
    }
//通过属性设置,可以在这个类上附加上自定义的helpattribute的信息。

3、作用:

那么,计算机是如果使用这些信息为以后更多的功能做准备呢?

下面做一个简单测试:

static void Main(string[] args)
        {
            HelpAttribute helpAttribute;
            foreach (var attribute in typeof(AnyClass).GetCustomAttributes(true))
            {
                helpAttribute = attribute as HelpAttribute;
                if (helpAttribute != null)
                {
                    Console.WriteLine(helpAttribute.Description);
                }
            }
            Console.ReadKey();
        }

另一个获取方式:

var classAttribute = (HelpAttribute)Attribute.GetCustomAttribute(typeof(AnyClass), typeof(HelpAttribute)); //在typeof(AnyClass)里面找typeof(HelpAttribute)即在所有属性里面寻找部分属性。
Console.WriteLine(classAttribute.Description);

 

最后说明,千里之行始于足下,九层之台起于累土,虽然只是皮毛,但是它是我进步的足迹,你我共勉。

 

posted @ 2017-06-22 19:26  田云  阅读(158)  评论(0编辑  收藏  举报