【C#】C# 扩展方法

今天在做一个功能的时候用到了扩展方法,想要得到一个字符串‘.’前面的字符

于是就这样写了

 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();

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C#中,扩展方法是一种特殊的静态方法,它允许您向现有的类型添加新的方法,而无需修改原始类型的定义。通过扩展方法,您可以在不创建新的派生类型或重新编译代码的情况下,为现有类型添加功能。 扩展方法的定义方式如下: ```csharp public static class ExtensionClass { public static ReturnType ExtensionMethod(this ExtendedType instance, parameters) { // 扩展方法的实现 } } ``` 其中,`ExtensionClass`是包含扩展方法的静态类,`ExtensionMethod`是扩展方法的名称,`ExtendedType`是要扩展的类型,`instance`是该类型的实例,`parameters`是方法的参数,`ReturnType`是方法的返回类型。 通过扩展方法,您可以像调用实例方法一样调用它们,而无需创建该类型的实例。例如,假设您想为字符串类型添加一个方法来反转字符串,可以使用扩展方法实现如下: ```csharp public static class StringExtensions { public static string Reverse(this string str) { char[] charArray = str.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } } ``` 然后,您可以在代码中使用该扩展方法: ```csharp string myString = "Hello World"; string reversedString = myString.Reverse(); // 调用扩展方法 Console.WriteLine(reversedString); // 输出:dlroW olleH ``` 扩展方法C#中非常有用,可以提高代码的可读性和灵活性,同时避免了修改原始类型的定义。它们经常用于扩展.NET框架中的基本类型,也可以用于自定义类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unity_阿黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值