我为用户和用户创建了两个简单的类,在类中,用户我只有userID、userName和List<string> userGroup
,在类用户中,我有两个用户的成员和两个属性来比较userGroup。
public List<string> DifferenceSetAtoB
{
get
{
return (List<string>)UserA.UserGroups.Except((List<string>)UserB.UserGroups);
}
}
我想做的是使用Except方法返回A和B之间的差集。
但当我运行代码时,我会在返回线上收到错误消息,上面写着:
System.InvalidCastExceptionHResult=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();
由于处理可能需要一些时间,因此它不应该是属性。尽管这只是一个设计选择的问题。