C#扩展方法

文档:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

说明:扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。我们平时用的最多的Linq语法里面就有很多的扩展方法,当然,我们也可以自定义属于你的扩展方法。

声明一个扩展方法:

  ①先看下普通的静态方法

  

 

 

②扩展方法就是在静态方法上进行了从新定义

 

 

我们也可以进行多个参数的定义:

例如:我们根据枚举的Name获取描述,和枚举的Name字符串获取描述(有时候我们调用的接口返回的就是枚举的字符串)

 #region  枚举的扩展方法
        /// <summary>
        /// 根据枚举值获取枚举描述
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns>描述字符串</returns>
        public static string EnumGetDescription(this Enum value)
        {
            var fi = value.GetType().GetField(value.ToString());
            if (fi != null)
            {
                var attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                        typeof(DescriptionAttribute), false); //获取描述的集合
                return attributes.Length > 0 ? attributes[0].Description : value.ToString(); //存在取第一个,不存在返回Name
            }
            return "";
        }

        /// <summary>
        /// 获取根据枚举名称获取枚举描述
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="enumName">枚举名称</param>
        /// <returns></returns>
        public static string EnumGetDescription<T>(this string enumName)
        {
            var fi = typeof(T).GetField(enumName);
            if (fi != null)
            {
                var attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                        typeof(DescriptionAttribute), false); 
                return attributes.Length > 0 ? attributes[0].Description : enumName; 
            }
            return "";     
        }
        #endregion
View Code

枚举的定义:

Enum用法:

 

 Mvc中的扩展也是一样的:

 

 Html:页面,都是Html的扩展

 

原文地址:https://www.cnblogs.com/Sea1ee/p/9526837.html