我正在尝试使用泛型来减少我的代码库,但遇到了这种情况。我似乎无法成功创建表达我正在尝试做的事情的谷歌查询。
本质上,我传递了一个泛型来制作一个 List<T>
然后传递 List<T>
进入需要 List<SpecificClass>
的函数
我的 JSONUser 类
public class JSONUser
{
public string DocumentId { get; set; }
[JsonProperty(PropertyName = "UserName", Required = Required.Always)]
public string UserName { get; set; }
[JsonProperty(PropertyName = "FirstName", Required = Required.AllowNull)]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "LastName", Required = Required.AllowNull)]
public string Lastname { get; set; }
}
假设有一个 JSONCompany 类,其中包含类似公司的字段。
主要代码:
static void CollectUserData()
{
boolean j = GetJSON<JSONUser>();
boolean k = GetJSON<JSONCompany>();
...
}
static boolean GetJSON<T>()
{
...
// Get the JSON in a List
List<T> oJSON = CallRest<T>();
// Now depending on the type passed in, call a different
// Process Function which expects a List<JSONUser> or
// List<JSONCompany> parameter
if (typeof(T) == typeof(JSONUser))
{
boolean result = ProcessUser(oJSON);
...
}
else if (typeof(T) == typeof(JSONCompany))
{
boolean result = ProcessCompany(oJSON);
...
}
...
}
public boolean ProcessUser(List<JSONUser> JSONList)
{
...
}
public boolean ProcessCompany(List<JSONCompany> JSONList)
{
...
}
在我调用 ProcessUser(oJSON);
之前一切都很好
它说没有接受通用的方法。当我尝试转换它时,它说
Cannot Covert Type
System.Collection.Generic.List<T>
toSystem.Collection.Generic.List<JSONUser>
希望这是清楚的。
最佳答案
如果ProcessUser
等人不需要一个列表并且可以只使用 IEnumerable<T>
那么你可以稍微简化一下:
public boolean ProcessUser(IEnumerable<JSONUser> JSONList)
{
...
}
public boolean ProcessCompany(IEnumerable<JSONCompany> JSONList)
{
...
}
然后调用它:
boolean result = ProcessUser(oJSON.Cast<JSONUser>());
否则您可以创建一个新列表:
boolean result = ProcessUser(oJSON.Cast<JSONUser>().ToList());
如果您只是迭代/修改列表中的对象而不是列表本身,这可能没问题。 (添加/删除/排序/等)
关于c# - 无法转换类型 System.Collection.Generic.List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32100144/