C#中关于Attribute的基本用法

本文介绍了一种使用C#反射来获取类方法上的自定义属性的方法,并通过具体实例展示了如何读取这些属性的值。这种方法可以用于元数据存储、命令行解析等多种场景。

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;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值