日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Net C# 扩展方法

發布時間:2024/7/19 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Net C# 扩展方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Net C# 擴展方法

擴展方法使您能夠向現有類型“添加”方法,而無需創建新的派生類型、重新編譯或以其他方式修改原始類型。擴展方法是一種特殊的靜態方法,但可以像擴展類型上的實例方法一樣進行調用。

好處:
不修改原有類型的實現

調用:
調用以成員函數方式調用,靜態實現

范例:
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);
??????? }
??? }
}

上述代碼實現的字統計

你也可以采用繼承的方式來實現

public class StringExtension : String
{
??? public int WordCount()
??? {
??? ......
??? }


調用上,這是兩個不同的類別處理。


=======================================================

看到這里,如果學習Objective-C,就知道Category這個東西,就是用于擴展方法。

看來C#這個語言,從多類語言中吸取各自的優點,混裝了自己~

至于Objective-C的Category,這里不做介紹和比對

=======================================================




轉載于:https://www.cnblogs.com/GoGoagg/archive/2011/08/04/2127697.html

總結

以上是生活随笔為你收集整理的Net C# 扩展方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。