System.Reflection 獲取描述

咱們須要獲取類,屬性,方法的描述。這個跟獲取枚舉的描述同樣,須要咱們經過反射來作。這還須要咱們的利用System.ComponentModel:Description  的屬性來完成。web

新建一個類:使用的是:  System.ComponentModel:Descriptionjson

 [Description("類的描述")]
    public class TestDes
    {
        [Description("id值")]
        public int Id { get; set; }


        [Description("名稱")]
        public string Name { get; set; }

        /// <summary>
        /// 方法描述
        /// </summary>
        [Description("方法描述2")]
        public void Eat()
        {
            string d = "";
        }

        /// <summary>
        /// 獲得方法重載
        /// </summary>
        [Description("方法描述3")]
        public void Eat(string aa)
        {
            string d = "";
        }
    }

 

 

三個擴展方法:api

   public static class Exl
    {
        /// <summary>
        /// 獲取類的描述
        /// </summary>
        /// <param name="t">類型</param>
        /// <returns></returns>
        public static string GetDescription(this Type t)
        {
            DescriptionAttribute[] attributes =
                   (DescriptionAttribute[])t.GetCustomAttributes(
                       typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : "";

        }

        /// <summary>
        /// 根據方法名獲取描述
        /// </summary>
        /// <param name="method">方法名</param>
        /// <param name="t">類型</param>
        /// <param name="types">參數類型</param>
        /// <returns></returns>      
        public static string GetDescriptionByMethod(this string method, Type t, params Type[] types)
        {

            System.Reflection.MethodInfo fi = t.GetMethod(method, types);
            if (fi != null)
            {
                DescriptionAttribute[] attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                        typeof(DescriptionAttribute), false);
                return attributes.Length > 0 ? attributes[0].Description : "";
            }
            return "";
        }

        /// <summary>
        /// 根據屬性獲取描述
        /// </summary>
        /// <param name="method">屬性名稱</param>
        /// <param name="t">類型</param>
        /// <returns></returns>
        public static string GetDescriptionByProperty(this string property, Type t)
        {
            System.Reflection.PropertyInfo fi = t.GetProperty(property);
            if (fi != null)
            {
                DescriptionAttribute[] attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                        typeof(DescriptionAttribute), false);
                return attributes.Length > 0 ? attributes[0].Description : "";
            }
            return "";
        }
    }

 

 

控制檯:app

 //獲取類 須要命名空間+類名
            Type t = Type.GetType("ReflectionDemo.TestDes");
            //Attribute[] dd = (Attribute[])t.GetCustomAttributes(typeof(Attribute), false);
            string classDes = t.GetDescription();
            string proDes = "Name".GetDescriptionByProperty(t);
            string meDes = "Eat".GetDescriptionByMethod(t);
            string meDes2 = "Eat".GetDescriptionByMethod(t, new Type[] { typeof(string) });
            Console.WriteLine($"類:TestDes:{classDes}");
            Console.WriteLine($"屬性:Name:{proDes}");
            Console.WriteLine($"方法:Eat:{meDes}");
            Console.WriteLine($"方法重載:Eat:{meDes2}");
            Console.ReadLine();

 

 

 

 

webapi中的異常過濾器:ide

 public class MyErrorFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            HttpActionContext context = actionExecutedContext.ActionContext;
            Type t = context.ControllerContext.Controller.GetType(); //獲得控制器的類型
            string controllerDes = t.GetDescription(); //控制器的描述
            string controllerName = context.ActionDescriptor.ControllerDescriptor.ControllerName;//控制器的名稱
            string actionName = context.ActionDescriptor.ActionName;//方法名
            string actionDes = actionName.GetDescriptionByMethod(t);//方法描述


            object obj = new
            {
                errcode = -1,
                errmsg = actionExecutedContext.Exception
            };
            actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented)
            {
                Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
            };
            ////2.返回調用方具體的異常信息
            //if (actionExecutedContext.Exception is NotImplementedException)
            //{
            //    actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            //}
            //else if (actionExecutedContext.Exception is TimeoutException)
            //{
            //    actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.RequestTimeout);
            //}
            ////.....這裏能夠根據項目須要返回到客戶端特定的狀態碼。若是找不到相應的異常,統一返回服務端錯誤500
            //else
            //{
            //    actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);

            //}
            base.OnException(actionExecutedContext);
        }
    }
相關文章
相關標籤/搜索