c# - 无法转换类型 System.Collection.Generic.List<T>

标签 c# generics

我正在尝试使用泛型来减少我的代码库,但遇到了这种情况。我似乎无法成功创建表达我正在尝试做的事情的谷歌查询。

本质上,我传递了一个泛型来制作一个 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> to System.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/

相关文章:

c# - 来自 SQLiteConnection 对象的 SQLite .dump 命令

c# - CreateLinkedTokenSource 抛出 ObjectDisposedException。如何正确安全地处置 CancellationTokenSource?

c# - 使用 content-type 与 webapicontrib.formatting.xlsx

c# - 将数据表转换为列表<T>

.net - IEnumerator<T>.Current 和 IEnumerator.Current 之间的关系以及为什么 IEnumerator<T> 实现 IDisposable

java - 什么是原始类型,为什么我们不应该使用它呢?

c# - CSV 文件中的新行

c# - 使用 .NET MVC Controller 操作作为 HTML <img> 的源

java 参数化泛型静态工厂

c# - Action /功能的通用列表