Attribute

作者:追风剑情 发布于:2014-7-17 22:09 分类:C#

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

标签: Attribute

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号