.NET 简单的扩展方法使用。

    写代码时,我们经常会碰到dll中提供的方法,不够用或者不好用的情况。而且我们也不方便去更改dll本身的源码。

这时候我们可以使用.NET提供的“扩展方法”去解决这个问题。

    下面我写几个简单的扩展方法在这里抛砖引玉,如有问题,请各位大大指正。

写代码时,我们经常会对string类型的数据进行操作,比如判断是否为null或者是否为空字符串

平时我写代码基本就是如下代码:

string str = GetName();

//第一种
if (str == null || str == "")
{

}

//第二种
if (string.IsNullOrEmpty(str))
{

}

这几种虽然也能判断字符串是否为空,但是用起来总是不太方便,我希望有一个“str.XXX()”的方法来直接判断是否为空

这时候我就可以用“扩展方法”来实现我的想法

因为我要为string类型加扩展方法,所以扩展方法类名字必须“原类名”+“Extensions”,并且是静态的。

所以这里我建立一个叫做“StringExtensions”的静态类。并写了一个IsNUllOrEmpty()的方法。

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsTest
{
    public static class StringExtensions
    {
        /// <summary>
        /// 判断字符串是否为null或""
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }
    }
}

现在我就可以直接调用这个扩展方法去判断字符串是否为空了。代码如下:

string str = GetName();

//调用字符串扩展方法
if (str.IsNullOrEmpty())
{

}

类似的例子有很多,比如我想要将字符串转成int类型,平时我都是用“int.TryParse(str, out result);”进行转型。

有了扩展方法后,我就可以在扩展方法里面写一些复杂的操作,比如直接使用str.ToInt()就可以进行转型操作。

如下是转成string装成int的代码(也包含了刚才判断为空的方法):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsTest
{
    public static class StringExtensions
    {
        /// <summary>
        /// 判断字符串是否为null或""
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        /// <summary>
        /// 字符串转int
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int ToInt(this string str) 
        {
            int outInt = 0;
            int.TryParse(str, out outInt);
            return outInt;
        }
    }
}

我经验比较初级,平时能用到的扩展方法,也只是类似这些简单的操作。不知道是不是有悖发明者的初衷,还是希望各位大大指正

原文地址:https://www.cnblogs.com/yinq/p/6248826.html