你真的了解C#扩展方法吗?

定义

微软对于扩展方法的定义是:

扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种静态方法,但可以像扩展类型上的实例方法一样进行调用。对于用 C#、F# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中定义的方法没有明显区别。

.

使用

首先我们定义一个简单类

 public class UserInfomation
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
    }

准备一些数据

实例化UserInformation对象

List<UserInfomation> lstUserInfomation = new List<UserInfomation> {  
                   new UserInfomation{Name="张三",Age=18,Sex="男" },
                   new UserInfomation{Name="李四",Age=19,Sex="男" },
                   new UserInfomation{Name="王五",Age=20,Sex="男" },
};

比如我们过滤出年龄大于19的数据并形成一个新的集合。

这时候大多数人都知道使用linq语句中的where方法

lstUserInfomation.Where(o => o.Age >= 19).ToList();

那如果我们现在要过滤出年龄大于19的数据并形成一个新的Json数据呢?

我们发现微软并没有实现ToJson。

可能有的Neter就说了,这个还不简单吗?

我们封装一个Jsonhelp类不就行了吗?

说干就干!

public static class JsonHelper
    {

        public static string ToJson(object obj)
        {
            return JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented,
            new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            });
        }
    }

使用

JsonHelper.ToJson(lstUserInfomation.Where(o => o.Age >= 19).ToList());

这样不就实现了吗?

确实,但是我觉得这样使用不够优雅,那么我们能不能简化一下,写成xxx.ToJson呢?

可能有的Neter就说了, 我们实现一个扩展方法不就行了吗?

扩展方法怎么定义呢?

扩展方法是静态类的静态方法,其实第一个参数用this修饰符代表源元素的类型。

那么我们把刚刚那个方法修改一下

public static class JsonHelper
    {
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented,
                new JsonSerializerSettings
                {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                });
        }
    }

使用

stUserInfomation.Where(o => o.Age >= 19).ToJson();

这样我们扩展方法就实现成功啦!