--- title: c#参数带this是什麼意思 tags: C#,open description: --- > [name=Jiesen] [time=20210902 ] [color=#907bf7] [TOC] # 前言 有看到這樣的寫法 public static int zzyhost(this String str) 參數型別前面加this,不知道為何這樣寫所以了解一下 # 說明 例如下列代码: ```C# namespace ExtensionMethods { public static class MyExtensions { public static string zzyhost(this String str,int number) { return 0; } } } ``` 那麼在其他類別下只需要 using ExtensionMethods;,所有 string 型別的物件就都有了 zzyhost() 這個方法,而無需重寫一個 string 類別,比如: ```C# using ExtensionMethods; ... //程式碼 string s = "Hello zzyhost"; //s=傳入參數String str ,5=傳入參數int number string i = s.zzyhost(5);//輸出 Hello zzyhost5 ``` # 心得整理 這是擴充方法的手法 寫擴充方法時 * ==類別==與==方法==必須為==static== * 方法的==第一個參數==會指定方法的==型別類型==,前面必須加上 ==this== 修飾詞 使用擴充方法時 * 在呼叫程式碼中,新增 using 指示詞以指定包含擴充方法類別的命名空間。 # 參考網站 [參考資料](https://zhidao.baidu.com/question/263333215940019885.html) [微軟官方](https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/classes-and-structs/extension-methods)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up