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

Chr*_*Den 5 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; }
    }
Run Code Online (Sandbox Code Playgroud)

假设有一个类 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)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

一切都很好,直到我打电话给 ProcessUser(oJSON);

它说没有方法接受泛型。当我尝试投射它时,它说

无法将类型System.Collection.Generic.List<T>转换为System.Collection.Generic.List<JSONUser>

希望这很清楚。

D S*_*ley 1

如果ProcessUseret al 不需要列表并且可以只使用 anIEnumerable<T>那么你可以稍微简化一下:

public boolean ProcessUser(IEnumerable<JSONUser> JSONList)
{
    ...
}

public boolean ProcessCompany(IEnumerable<JSONCompany> JSONList)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后只需调用它:

boolean result = ProcessUser(oJSON.Cast<JSONUser>());
Run Code Online (Sandbox Code Playgroud)

否则你可以创建一个新列表:

boolean result = ProcessUser(oJSON.Cast<JSONUser>().ToList());
Run Code Online (Sandbox Code Playgroud)

如果您只是迭代/修改列表中的对象而不是列表本身,这可能没问题。(添加/删除/排序/等)