C# Attributes

原文

声明

使用

通过反射得到Attributes

using System;

namespace CSharpTutorials
{
    // 声明
    [AttributeUsage(AttributeTargets.All)]
    public class HelpAttribute : System.Attribute
    {
        public string Topic { get; set; }
        public string Url { get;}

        // 构造函数
        public HelpAttribute(string url)  // url is a positional parameter
        {
            Url = url;
        }
    }


    // 使用
    [HelpAttribute("http:blog.csdn.net/yemeishenme")]
    class MyClass
    {

    }


    // 通过反射得到

    class @Entry
    {
        static void Main(string[] args)
        {
            System.Reflection.MemberInfo info = typeof(MyClass);
            object[] attributes = info.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length; i++)
            {
                Console.WriteLine(attributes[i]);
                var s = attributes[i] as HelpAttribute;
                Console.WriteLine(s.Url);
            }
        }
    }
}

你可能感兴趣的:(C#)