您的位置:首页 > 编程语言 > C#

【C#】C# 扩展方法

2017-08-25 15:27 183 查看
今天在做一个功能的时候用到了扩展方法,想要得到一个字符串‘.’前面的字符

于是就这样写了

public static string RomovePointString( string content)
{
if (content.Contains("."))
{
string str = content.Split('.')[0];
return str;
}
Debug.LogError("不包含 .");
return null;
}


这样子调用 TxtUtility.RomovePointString("string") 因为是个静态方法

后来使用了扩展方法
   public static string RomovePointString(this string content)

    {

        if (content.Contains("."))

        {

            string str = content.Split('.')[0];

            return str;

        }

        Debug.LogError("不包含 .");

        return null;

    }

在静态方法的参数中加入 this ,后来的调用方式就变成





扩展方法的具体含义:

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

大家可以在MSDN上查看到 

扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 仅当你使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。

比如

namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}

当你使用时

using
ExtensionMethods

string s = "Hello Extension Methods";
int i = s.WordCount();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: