鸟语天空
Attribute
post by:追风剑情 2014-7-17 22:09

using System;
using System.Reflection;

namespace AttributeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            AnimalTypeTestClass testClass = new AnimalTypeTestClass();
            Type type = testClass.GetType();
            // 遍历类中的所有字段
            foreach (FieldInfo fInfo in type.GetFields())
            {
                // 遍历字段上绑定的所有特性
                foreach (Attribute attr in Attribute.GetCustomAttributes(fInfo))
                {
                    if (attr.GetType() == typeof(AnimalTypeAttribute))
                        Console.WriteLine(
                            "Field Name={0} Description={1} attribute.",
                            fInfo.Name, ((AnimalTypeAttribute)attr).Description);
                }

            }

            Console.ReadKey();
        }
    }

    public class AnimalTypeAttribute : Attribute
    {
        protected string _description;

        public AnimalTypeAttribute(string description)
        {
            _description = description;
        }

        public string Description
        {
            get
            {
                return _description;
            }
        }
    }

    class AnimalTypeTestClass
    {
        [AnimalType("名字")]
        public string Name;

        [AnimalType("年龄")]
        public string Year;
    }
}

运行效果

Attribute运行效果.png

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容