ActionAttribute.cs 1.66 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Hh.Mes.Service.WebService.Planned
{
    /// <summary>
    /// 标识该方法是否为ActionAttribute
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
    public class ActionAttribute : Attribute
    {
        /// <summary>
        /// Action的调用名称(key)
        /// </summary>
        public string Name { get; set; }

        public ActionAttribute(string name)
        {
            this.Name = name;
        }

        public ActionAttribute()
        {

        }
        /// <summary>
        /// 获取指定类的方法
        /// 方法必须标记 ActionAttribute
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Dictionary<string, MethodInfo> GetMethods(Type type)
        {
            if (type == null) return null;
            Dictionary<string, MethodInfo> dic = new Dictionary<string, MethodInfo>();
            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
            foreach (MethodInfo method in methods)
            {
                var attr = method.GetCustomAttributes(false).FirstOrDefault(x => x.GetType().Name == nameof(ActionAttribute));
                if (attr == null) continue;
                var temp = attr.GetType().GetProperty("Name")?.GetValue(attr);
                var key = temp != null ? temp.ToString() : method.Name;
                dic.Add(key, method);
            }
            return dic;
        }
    }
}