C# Extension Methods

本文详细介绍了C#中的扩展方法,包括如何定义扩展方法、使用静态类包含这些方法以及如何调用它们。通过实例展示了将现有类的功能进行扩展而不必创建新的派生类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In C#, extension methods enable you to add methods to existing class without creating a new derived class.

Extension methods 要求:

  1. Define a static class to contain extension method. This class must be visible to client code.
  2. Implement the extension method like a static method, but add "this" modifier before the first parameter.
  3. The first parameter specifies the type that this extension method operates on.
 1 using System.Globalization;
 2 using System.Threading;
 3 
 4 namespace Library
 5 {
 6     public static class StringExtensions
 7     {
 8         //static method
 9         //public static string ConvertToTitleCase(this string source)
10         //extension method
11         public static string ConvertToTitleCase(this string source)
12         {
13             CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
14             TextInfo textInfo = cultureInfo.TextInfo;
15 
16             return textInfo.ToTitleCase(source);
17         }
18     }
19 }

 

Extension methods call:

 Call extension method  like extension method is an instance method on the type.

 1 namespace Library_Simple
 2 {
 3     //Import extension method namespace
 4     using Library;
 5     class Program
 6     {
 7         static void Main(String[] args)
 8         {
 9             string source = "the return of the king";
10             string extected = "The Return Of The King";
11 
12             //static method
13             //string result = StringExtensions.ConvertToTitleCase(source);
14             //extension method
15             string result = source.ConvertToTitleCase();
16 
17             Assert.IsNotNull(result);
18             Assert.AreEqual(expected, result);
19         }
20     }
21 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5958925.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值