Re: [問題] 有無動態指定泛型型別的寫法

看板C_Sharp (C#)作者時間8年前 (2017/01/10 02:14), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《aoksc (重出江湖)》之銘言: : 請問各位 : 假設拿Json.net來當例子 : Json.net的Deserialize有DeserializeObject的方法 : Account account = JsonConvert.DeserializeObject<Account>(json); : 我指定了<Account>所以Deserialize出來的結果就是Account的Model : 但我可能有10多的model要Deserialize : 只差在type不同 : 所以請問有什麼寫法可以讓我在泛型部份可以像變數一樣使用的嘛? : 例如一個方法我可以從外面傳入一個我要指定的泛型型別 : 謝謝 Google "variable generics c#" First hyperlink is solution. "The point about generics is to give compile-time type safety - which means that types need to be known at compile-time." "You can call generic methods with types only known at execution time, but you have to use reflection." This is example: <code> using System; using System.Windows.Forms; using Newtonsoft.Json; using System.Reflection; using System.Linq; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); Tuple<Type, string>[] jsons = new Tuple<Type, string>[3]; jsons[0] = new Tuple<Type, string>(typeof(Apple), JsonConvert.SerializeObject(new Apple("Apple123"))); jsons[1] = new Tuple<Type, string>(typeof(Ball), JsonConvert.SerializeObject(new Ball(45.6))); jsons[2] = new Tuple<Type, string>(typeof(Cat), JsonConvert.SerializeObject(new Cat(9))); foreach (Tuple<Type, string> json in jsons) { object obj = MyDeserializeObject(json.Item1, json.Item2); MessageBox.Show("Type = " + obj.GetType().ToString() + ", Content = " + obj.ToString()); } } public static object MyDeserializeObject(Type type, string json) { MethodInfo method = typeof(JsonConvert).GetMethods().Where(m => m.Name == "DeserializeObject" && m.IsGenericMethod).First().MakeGenericMethod(new Type[] { type }); return method.Invoke(null, new object[] { json }); } private class Apple { public Apple(string name) { this.name = name; } [JsonProperty] public string name; public override string ToString() { return this.name; } } private class Ball { public Ball(double x) { this.x = x; } [JsonProperty] public double x; public override string ToString() { return this.x.ToString(); } } private class Cat { public Cat(int tail) { this.tail = tail; } [JsonProperty] public int tail; public override string ToString() { return this.tail.ToString(); } } } } </code> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.240.24.170 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1483985650.A.9CA.html

01/10 22:44, , 1F
感謝分享 收穫很多!
01/10 22:44, 1F
文章代碼(AID): #1OSzBodA (C_Sharp)
文章代碼(AID): #1OSzBodA (C_Sharp)