1. 程式人生 > >C#中關於Attribute的基本用法

C#中關於Attribute的基本用法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            MethodInfo method = typeof(Operation).GetMethod("Add");
            Attribute[] atts = Attribute.GetCustomAttributes(method);
            foreach (Attribute att in atts)
            {
                if (att.GetType() == typeof(CommandAttribute))
                {
                    Console.WriteLine(((CommandAttribute)att).Name + "," + ((CommandAttribute)att).Label);
                }
            }
            Console.ReadLine();
            return;

            #region 獲取所有的方法屬性

            Operation testClass = new Operation();
            Type type = testClass.GetType();
            // Iterate through all the methods of the class.
            foreach (MethodInfo mInfo in type.GetMethods())
            {
                // Iterate through all the Attributes for each method.
                foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
                {
                    // Check for the AnimalType attribute.
                    if (attr.GetType() == typeof(CommandAttribute))
                        Console.WriteLine(
                            "Method {0} has a CommandAttribute {1},{2} .",
                            mInfo.Name, ((CommandAttribute)attr).Label, ((CommandAttribute)attr).Name);
                }
            }

            #endregion



            Console.ReadLine();
        }
    }

    public class Operation
    {
        [CommandAttribute("AddLabel", "AddName")]
        public void Add()
        {
            Console.WriteLine("Add");
        }

        [CommandAttribute("DelLabel", "DelName")]
        public void Del()
        {
            Console.WriteLine("Del");
        }
    }

    [AttributeUsage(AttributeTargets.Method)]
    public class CommandAttribute : Attribute
    {
        public string Label { get; set; }
        public string Name { get; set; }

        public CommandAttribute() { }

        public CommandAttribute(string label, string name)
        {
            this.Label = label;
            this.Name = name;
        }
    }
}