将类型'System.Collections.Generic.List <string>'转换为'System.Collections.Generic.IList&lt;&gt;'

时间:2016-01-21 07:49:35

标签: c# generics

在我的模型Account中,我有一个像这样的属性

public List<String> Roles { get; set; }

后来我想获得该属性但转换它IList<IApplicationUserRole<Role>>,所以我有这个功能

 public IList<IApplicationUserRole<Role>> Roles
    {
        get
        {
            return _account.Roles; // how do I convert this in the specific type intended. 
        }
    }

这是我的IApplicationUserRole

public interface IApplicationUserRole<TRoleModel> : IRole<string>
    where TRoleModel : EntityModel
{
    TRoleModel Role { get; set; }

    String Name { get; set; }
}

我是这件事的新手。期待任何帮助。

2 个答案:

答案 0 :(得分:3)

假设你的实现类是这样的:

public class ApplicationUserRole : IApplicationUserRole<T> where T : Role
{
    public ApplicationUserRole()
    {
    }
    public User User { get; set; }
    public T Role { get; set; }
}

然后,你会做这样的事情:

public IList<IApplicationUserRole<Role>> Roles
{
    get
    {
        return _account.Roles
            .Select(r => new ApplicationUserRole { Role = roleService.FindRoleByName(r) })
            .Cast<IApplicationUserRole<Role>>()
            .ToList(); 
    }
}

其中roleService是从角色名称构建Role实例的某种方式(上面是r

注意:这就是说,上面的实现中有一个 catch 。由于Roles是属性,因此不应执行数据访问操作。因此,在这种情况下,您应该创建一个方法而不是属性。

答案 1 :(得分:1)

我会从这样的事情开始:

apt-get -f install

这假设您有一个实现public IList<IApplicationUserRole<Role>> Roles { get { return _account.Roles.Select(r=> new ApplicationUserRole<Role>() {Name = r}) .Cast<IApplicationUserRole<Role>>() .ToList(); } } 接口的类。

由于@MartinLiversage表示您无法直接将IApplicationUserRole<Role>转换为List<T>,因此您必须手动进行转换。