用法1 this代表當前類的實例對象 當我們定義了一個類的全局變量時 而該類方法中也聲明了相同的參數名時 如何區分兩個相同參數名稱的調用 使用this可以更直觀地看到this.參數名 為全局參數。
首先聲明一個類
public class TestThisClass { //用法一 this代表當前類的實例對象 private string scope = "全局變量"; public string getResult() { string scope = "局部變量"; // this代表TestThisClass的實例對象 // 所以this.scope對應的是全局變量 // scope對應的是getResult方法內的局部變量 return this.scope + "-" + scope; } }
我在mian函數中使用
public static void Main(string[] args) { //用法一 this代表當前類的實例對象 TestThisClass testThisClass = new TestThisClass(); Console.WriteLine(testThisClass.getResult()); }
輸出結果 注意是先全局變量再局部變量

用法2 用this串聯構造函數 (:this()方法) 目的是為了實例化該類時 還會先自動調用一次base()中對應參數的方法類 再繼續執行原本的方法
首先聲明一個類
public class TsetThisCLClass { public TsetThisCLClass() { Console.WriteLine("無參構造函數"); } // this()對應有兩個參構造方法TsetThisCLClass(string text, string text2) // 先執行TsetThisCLClass(string text, string text2),后執行TsetThisCLClass(string text) public TsetThisCLClass(string text) : this("李四", text) { Console.WriteLine(text); Console.WriteLine("有參構造函數"); } public TsetThisCLClass(string text, string text2) { Console.WriteLine(text + text2); Console.WriteLine("有兩個參數的參構造函數"); } }
我在mian函數中使用、
//用法二 用this串聯構造函數 (:base()方法) TsetThisCLClass test = new TsetThisCLClass("張三");
輸出結果 注意是先輸出base中帶兩個參數的方法 再輸出本身

用法3 為原始類型擴展方法 主要是用來我們平時經常用到的類型 (string,object)
首先聲明一個擴展類
public static class Extends { // string類型擴展ToJson方法 public static object stringToJson(this string Json) { return Json == null ? null : JsonConvert.DeserializeObject(Json); } // object類型擴展ToJson方法 public static string objectToJson(this object obj) { var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; return JsonConvert.SerializeObject(obj, timeConverter); } }
具體調用
object a = "asjfh"; string b = "afsdd"; a.objectToJson(); //這里的a是object類型 他可直接調用擴展方法 this object方法中聲明的內容 b.stringToJson(); //這里的b是string類型 他可直接調用擴展方法 this string方法中聲明的內容

舉個例子 .net core注入配置文件 使用this 方法
public void ConfigureServices(IServiceCollection services) { var builder = new ConfigurationBuilder(); builder.AddJsonFile($"{AppDomain.CurrentDomain.BaseDirectory}/A.json", false, true); var config = builder.Build(); services.AddAlhgInfoConf(config);//調用下面的方法 }
再聲明一個方法
//這里的方法 聲明了參數 this IServiceCollection services 所以上面的services可以直接調用AddAlhgInfoConf該方法 這是屬於this的擴展方法 public static IServiceCollection AddAlhgInfoConf(this IServiceCollection services, IConfiguration configuration) { services.Configure<AlhgInfoConf>(configuration); return services; }
