C# 当我知道隐藏在它后面的类时,如何返回T?
我知道T是C# 当我知道隐藏在它后面的类时,如何返回T?,c#,reflection,types,abstract,leaky-abstraction,C#,Reflection,Types,Abstract,Leaky Abstraction,我知道T是List(或者List)。反射或允许我返回此字符串列表的东西的外观如何 public T Deserialize<T>(string response) { //just example string[] words = response.Split(' '); List<string> wordsList = words.ToList(); //? return wordsList; } public T反序列化(字符
List
(或者List
)。反射或允许我返回此字符串列表的东西的外观如何
public T Deserialize<T>(string response)
{
//just example
string[] words = response.Split(' ');
List<string> wordsList = words.ToList();
//?
return wordsList;
}
public T反序列化(字符串响应)
{
//举个例子
string[]words=response.Split(“”);
列表单词列表=words.ToList();
//?
返回单词列表;
}
背景:反序列化方法用于解析html数据。这类似于网站中使用的myJson.myDeserialize方法,它没有API。实现这一点有一个棘手的技巧:您需要首先将实例强制转换为
对象
public T Deserialize<T>(string response)
{
string[] words = response.Split(' ');
List<string> wordsList = words.ToList();
return (T)(object)wordsList;
}
public T反序列化(字符串响应)
{
string[]words=response.Split(“”);
列表单词列表=words.ToList();
返回(T)(对象)单词列表;
}
这假设调用者指定List
作为泛型类型
var x = Deserialize<List<string>>("hello world"); // gives "hello", "world"
var y = Deserialize<int>("hello world"); // throws InvalidCastException
var x=反序列化(“hello world”);//给出“你好”,“世界”
var y=反序列化(“hello world”);//抛出InvalidCastException
如果您需要返回List
为什么不将返回类型标记为List
?如果T
是List
,那么您希望列表的内容是什么?这个问题有标记抽象,但我认为应该标记为泄漏抽象反序列化方法用于解析html数据。这类似于网站中使用的myJson.myDeserialize方法,它没有API。