繁体   English   中英

如何在 List 中转换对象类型<t> 。除了

[英]How to cast the object type in List<t>.Except

我为用户和用户创建了两个简单的类,在用户类中我只有 userID、userName 和List<string> userGroup ,在用户类中我有两个用户的成员和两个属性来比较用户组。

        public List<string> DifferenceSetAtoB
        {
            get
            {
                return (List<string>)UserA.UserGroups.Except((List<string>)UserB.UserGroups);
            }
        }

我想要做的是使用 except 方法返回 A 和 B 之间的差异集。

但是当我运行代码时,我会在返回行收到错误消息:

System.InvalidCastException HResult=0x80004002 消息=无法将类型“d__81 1[System.String]' to type 'System.Collections.Generic.List 1[System.String]”。

我的理解是UserB.UserGroups的数据类型是List,当我使用Except时它是Collection中的一个方法,所以数据类型是Collections.General.List。 但我不知道如何强制数据类型相同。 List 不是已经来自 System.Collections.Generic 了吗? 有人可以帮忙吗?

完整代码如下:

    public class User
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public List<string> UserGroups { get; set; }

        public User()
        {
            this.UserGroups = new List<string>();
        }
    }

    public class UserComparison
    {
        public User UserA { get; set; }
        public User UserB { get; set; }

        public List<string> DifferenceSetAtoB
        {
            get
            {
                return (List<string>)UserA.UserGroups.Except((List<string>)UserB.UserGroups);
            }
        }
        public List<string> DifferenceSetBtoA
        {
            get
            {
                return (List<string>)UserB.UserGroups.Except((List<string>)UserA.UserGroups);
            }
        }

        public UserComparison()
        {
            this.UserA = new User();
            this.UserB = new User();
        }
    }

Except(...)返回IEnumerable<>因此强制转换无效。 如果要返回列表,可以使用ToList()方法:

return UserA.UserGroups.Except(UserB.UserGroups).ToList();

由于可能需要一些时间来处理,它不应该是财产。 虽然这只是设计选择的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM