【C#】C# 扩展方法
2017-08-25 15:27
183 查看
今天在做一个功能的时候用到了扩展方法,想要得到一个字符串‘.’前面的字符
于是就这样写了
这样子调用 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 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。
比如
当你使用时
using
ExtensionMethods
于是就这样写了
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();
相关文章推荐
- C#扩展方法
- C#原始类型扩展方法—this参数修饰符
- C#基础:通过一个实例来学习IFormattable接口,扩展方法
- c#扩展方法奇思妙用高级篇二:Aggregate扩展其改进
- C#扩展方法
- 【C#】扩展方法的应用
- C#中如果类的扩展方法和类本身的方法签名相同,那么会优先调用类本身的方法
- C# TextBox 扩展方法数据验证
- C# 方法中的this参数--.NET3.5类型的扩展方法
- C# 扩展方法应用二:文件操作
- C# 扩展方法
- C#扩展方法
- c#扩展方法奇思妙用基础篇二:string 常用扩展
- C#学习笔记(三)—–C#高级特性:扩展方法
- C#.NET扩展方法
- c# 扩展方法奇思妙用性能篇一:扩展方法性能初测
- C#中扩展方法
- C#扩展方法本质
- 扩展方法(C# 编程指南)
- C# 3.0 新特性 学习(二):匿名类型、扩展方法