日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

Net C# 扩展方法

發布時間:2024/7/19 C# 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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# 扩展方法的全部內容,希望文章能夠幫你解決所遇到的問題。

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