C#原始类型扩展方法—this参数修饰符
来源:互联网 发布:yum心意美食卡介绍 编辑:程序博客网 时间:2024/04/28 02:22
扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。仅当您使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。
下面的示例演示为 System.String 类定义的一个扩展方法。请注意,它是在非嵌套、非泛型静态类内部定义的:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
可使用以下 using 指令将 WordCount 扩展方法放入范围中:
using ExtensionMethods;
而且,可以在应用程序中使用以下语法对该扩展方法进行调用:
string s = "Hello Extension Methods";
int i = s.WordCount();
在代码中,可以使用实例方法语法调用该扩展方法。但是,编译器生成的中间语言 (IL) 会将代码转换为对静态方法的调用。因此,并未真正违反封装原则。实际上,扩展方法无法访问它们所扩展的类型中的私有变量。
定义和调用扩展方法:
1、定义一个静态类以包含扩展方法。该类必须对客户端代码可见。有关可访问性规则的更多信息,请参见访问修饰符(C# 编程指南)。
2、将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
3、该方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。
4、在调用代码中,添加一条 using 指令以指定包含扩展方法类的命名空间。
5、按照与调用类型上的实例方法一样的方式调用扩展方法。
请注意,第一个参数不是由调用代码指定的,因为它表示正应用运算符的类型,并且编译器已经知道对象的类型。您只需通过 n 为这两个形参提供实参。
示例
下面的示例在 MyExtensions.StringExtension 类中实现了一个名为 WordCount 的扩展方法。该方法对 String 类进行操作,而该类被指定为第一个方法参数。MyExtensions 命名空间被导入到应用程序命名空间中,并且该方法是在 Main 方法内调用的。
using System.Linq;
using System.Text;
using System;
namespace CustomExtensions
{
//Extension methods must be defined in a static class
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
namespace Extension_Methods_Simple
{
//Import the extension method namespace.
using CustomExtensions;
class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
// Call the method as if it were an
// instance method on the type. Note that the first
// parameter is not specified by the calling code.
int i = s.WordCount();
System.Console.WriteLine("Word count of s is {0}", i);
}
}
}
- C#原始类型扩展方法—this参数修饰符
- C#原始类型扩展方法—this参数修饰符
- C#原始类型扩展方法—this参数修饰符
- C#原始类型扩展方法—this参数修饰符
- 原始类型扩展方法—this参数修饰符
- 【转】C#原始类型扩展方法—this参数修饰符
- C#类型扩展方法—this参数修饰符
- C#中this用法系列(二) 通过this修饰符为原始类型扩展方法
- C# 方法中的this参数--.NET3.5类型的扩展方法
- C#方法参数修饰符
- MSDN---扩展方法 (C# 方法中的this参数)
- C# 参数带this是什么意思(扩展方法)
- C#的方法的参数修饰符详解
- C#学习笔记--方法和参数修饰符
- C# 方法中的this参数
- C# 方法中的this参数
- C# 方法中的this参数
- C#参数修饰符总结
- GitHub项目推介_XLog
- 现实地讲, 数组和指针地区别是什么?
- Xsolla全新帐户管理工具————分析报告
- 马云入股恒大背后暗藏四大隐情?
- 一、ExtJS下载使用
- C#原始类型扩展方法—this参数修饰符
- Populating Next Right Pointers in Each Node
- 计算机网络笔记---网络层---内部网关协议RIP
- inner static class 和Constructor优先调用次序问题
- SELECT语句常用字句的用法
- jbpm4.4学习总结(三)常用接口使用说明
- RSA padding schemes
- python编写的串口程序
- CCT之CAMERA TUNNING调试学习总结