首页 > 其他 > 详细

C# 特性(attribute)

时间:2014-04-26 09:36:13      阅读:479      评论:0      收藏:0      [点我收藏+]

Atrribute表示自定义特性的基类。

其派生类约定惯例以Attribute结尾命名,如:AttributeUsageAttribute、TestAttribute。

下面获取如何定制特性attribute和获取自定义特性信息:

bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace AttributeDemo
{
    [Test("it‘s a class1")]
    [Test("it‘s a class2")]
    [Test("it‘s a class3")]
    class Program
    {
        [Test("it‘s a property")]
        public String Name { get; set; }

        static void Main(string[] args)
        {
            Program p = new Program();

            Type type = typeof(Program);
            MethodInfo method = type.GetMethod("AttributeTest");
            MemberInfo member = type.GetMember("Name").First();

            //利于反射分别获取类、方法、属性的算定义特性实例化
            TestAttribute[] myAttr = (TestAttribute[])Attribute.GetCustomAttributes(type, typeof(TestAttribute));
            TestAttribute myAttr2 = (TestAttribute)Attribute.GetCustomAttribute(method, typeof(TestAttribute));
            TestAttribute myAttr3 = (TestAttribute)Attribute.GetCustomAttribute(member, typeof(TestAttribute));

            foreach (TestAttribute attr in myAttr)
            {
                Console.WriteLine(attr.Message);//输出类Program的自定义特性
            }
            Console.WriteLine(myAttr2.Message); //输出方法AttributeTest的自定义特性

            Console.WriteLine(myAttr3.Message); //输出属性Name的自定义特性

            //调用方法AttributeTest
            object obj = Activator.CreateInstance(typeof(Program));
            method.Invoke(obj, null);

            
        }

        [Test("it‘s a method")]
        public void AttributeTest()
        {
            Console.WriteLine("我还可以这样被调用");
        }
    }

    [AttributeUsageAttribute(AttributeTargets.All,AllowMultiple=true,Inherited=true)]
    public class TestAttribute : Attribute
    {
        public String Message { get; set; }
        public TestAttribute(string message)
        {
            this.Message = message;
        }
    }
}
bubuko.com,布布扣

 

C# 特性(attribute),布布扣,bubuko.com

C# 特性(attribute)

原文:http://www.cnblogs.com/MrHacker/p/3452813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!