C# 无法隐式转换类型';System.Collections.IList';至';System.Collections.Generic.List
这就是我遇到的错误 错误1无法将类型C# 无法隐式转换类型';System.Collections.IList';至';System.Collections.Generic.List,c#,.net,generics,C#,.net,Generics,这就是我遇到的错误 错误1无法将类型System.Collections.Generic.IList隐式转换为System.Collections.Generic.List。存在显式转换(是否缺少强制转换?) 我的代码: IList<RoleDTO> rl = new List<RoleDTO>(); rl.Add(new RoleDTO{ roleId = new Guid("D3DCBCDA-AD61-4764-B5A1-057D654F1C26")
System.Collections.Generic.IList
隐式转换为System.Collections.Generic.List
。存在显式转换(是否缺少强制转换?)
我的代码:
IList<RoleDTO> rl = new List<RoleDTO>();
rl.Add(new RoleDTO{ roleId = new Guid("D3DCBCDA-AD61-4764-B5A1-057D654F1C26"),
role = "admin" });
UserDTO user = new UserDTO
{
username = "administrator",
email = "administrator@email.com",
role = rl
};
IList rl=new List();
rl.Add(新角色到{roleId=新Guid(“D3DCBCDA-AD61-4764-B5A1-057D654F1C26”),
role=“admin”});
UserDTO user=新UserDTO
{
用户名=“管理员”,
电子邮件=”administrator@email.com",
角色=rl
};
模型:
namespace Model.DTO
{
public class UserDTO
{
public string username { get; set; }
public string email { get; set; }
public IList<RoleDTO> role { get; set; }
}
public class RoleDTO
{
public Guid roleId { get; set; }
public string role { get; set; }
}
}
namespace Model.DTO
{
公共类UserDTO
{
公共字符串用户名{get;set;}
公共字符串电子邮件{get;set;}
公共IList角色{get;set;}
}
公共类角色
{
公共Guid roleId{get;set;}
公共字符串角色{get;set;}
}
}
如何正确地执行此操作 只需将
r1
更改为IList
IList rl=new List();
不能混合使用泛型列表和非泛型列表,因为IList
不继承自IList
,List
不继承自List
,并且不实现IList
编辑
根据新的错误,这意味着您正在尝试将
IList
转换为列表
,这不能隐式完成,因为任何人都可以编写实现IList
的类。因此,您要么需要执行显式强制转换,要么更改类型以匹配。问题在于,当前代码没有在任何地方显示IList
正被隐式转换为列表
。但我有一些猜测。如果UserDTO.roles
实际上被定义为List
而不是IList
,那么只需将r1
更改为List
或将UserDTO.roles
更改为IList
。我更喜欢后者。如果要将UserDTO.roles
分配给List
类型的变量,则应将该变量的类型改为IList
。只需更新
rl.Add(new UserDTO { roleId = new Guid("D3DCBCDA-AD61-4764-B5A1-057D654F1C26"), role = "admin" });
与
您正在将rl声明为
IList
,而不是IList
更改此项:
IList rl = new IList<RoleDTO>();
IList rl=新IList();
为此:
IList<RoleDTO> rl = new List<RoleDTO>
IList rl=新列表
错误很明显。您将rl
声明为非泛型IList
,同时尝试将其分配给UserDTO.role
中的IList
。只需将IList rl
的声明更改为IList
。我编辑了输入错误,也得到了这个错误:错误1无法将类型“System.Collections.Generic.IList”隐式转换为“System.Collections.Generic.List”。存在显式转换(是否缺少强制转换?)每个列表
都是IList
,但不是相反。基于编辑,我假设public-IList角色{get;set;}
实际上是public-List角色{get;set;}
。仔细阅读错误。我没有发现此代码有任何错误。这是一个打字错误,不是问题中所问错误的来源。非常感谢先生:)@barrypicker不知为什么没有正确显示我的答案,我只是将相关部分标记为“代码”,现在显示为ok。
IList rl = new IList<RoleDTO>();
IList<RoleDTO> rl = new List<RoleDTO>