Re: [问题] 有无动态指定泛型型别的写法

楼主: pzyc79   2017-01-10 02:14:05
※ 引述《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>
作者: aoksc (重出江湖)   2017-01-10 22:44:00
感谢分享 收获很多!

Links booklink

Contact Us: admin [ a t ] ucptt.com