C# this关键字的3种用法
生活随笔
收集整理的這篇文章主要介紹了
C# this关键字的3种用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用法一 ?this代表當前類的實例對象
namespace Demo {public class Test{private string scope = "全局變量";public string getResult(){string scope = "局部變量";// this代表Test的實例對象// 所以this.scope對應的是全局變量// scope對應的是getResult方法內的局部變量return this.scope + "-" + scope;}}class Program{static void Main(string[] args){try{Test test = new Test();Console.WriteLine(test.getResult());}catch (Exception ex){Console.WriteLine(ex);}finally{Console.ReadLine();}}} }用法二 ?用this串聯構造函數
namespace Demo {public class Test{public Test(){Console.WriteLine("無參構造函數");}// this()對應無參構造方法Test()// 先執行Test(),后執行Test(string text)public Test(string text) : this(){Console.WriteLine(text);Console.WriteLine("有參構造函數");}}class Program{static void Main(string[] args){try{Test test = new Test("張三");}catch (Exception ex){Console.WriteLine(ex);}finally{Console.ReadLine();}}} }用法三 ?為原始類型擴展方法
namespace Demo {public static class Extends{// string類型擴展ToJson方法public static object ToJson(this string Json){return Json == null ? null : JsonConvert.DeserializeObject(Json);}// object類型擴展ToJson方法public static string ToJson(this object obj){var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };return JsonConvert.SerializeObject(obj, timeConverter);}public static string ToJson(this object obj, string datetimeformats){var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };return JsonConvert.SerializeObject(obj, timeConverter);}public static T ToObject<T>(this string Json){return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);}public static List<T> ToList<T>(this string Json){return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);}public static DataTable ToTable(this string Json){return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);}public static JObject ToJObject(this string Json){return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("?", ""));}}class Program{static void Main(string[] args){try{List<User> users = new List<User>{new User{ID="1",Code="zs",Name="張三"},new User{ID="2",Code="ls",Name="李四"}};// list轉化json字符串string json = users.ToJson();// string轉化Listusers = json.ToList<User>();// string轉化DataTableDataTable dt = json.ToTable();}catch (Exception ex){Console.WriteLine(ex);}finally{Console.ReadLine();}}}public class User{public string ID { get; set; }public string Code { get; set; }public string Name { get; set; }} }總結
以上是生活随笔為你收集整理的C# this关键字的3种用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET 中的 Worker Servi
- 下一篇: C# 强大的新特性 Source Gen