【发布时间】:2013-12-07 14:54:01
【问题描述】:
将 Reflection 返回的通用实体集转换为具有 BaseClass 类型的实体集时遇到问题。
我所有的 Linq2Sql 类都继承自一个名为 LinqClassBase 的基类,如下所示:
public partial class MyTable1 : LinqClassBase
我正在该基类中编写一个需要遍历所有子实体集的方法。
我可以将 PropertyInfo OK 检索为 matchingEntitySetProperty。
// The GetMatchingProperty method (not shown)
// simply gets all the properties with Type EntitySet
var matchingProperty = entitySetProperty.GetMatchingProperty(this.GetType());
我也可以得到它的价值。
// This returns EntitySet<MyTable1>
var matchingSet = matchingProperty.GetValue(this);
这里的问题是我不能调用 ToList 方法,因为对象不是强类型的。
var newList = matchingSet.ToList().ConvertAll(
x => x.MyLinqBaseClassMethod()
);
我尝试将其转换为 EntitySet 但它返回 null:
// This returns null
var matchingSet = matchingProperty.GetValue(this) as EntitySet<LinqClassBase>;
为什么这个强制转换返回 null?我猜是因为 C# 不能将 EntitySet 转换为 EntitySet。
如果无法进行此演员阵容,还有其他方法可以演员吗?
注意:我曾考虑过使用另一层反射来调用 ToList 方法,但随后我会在 ConvertAll 方法和 MyLinqBaseClassMethod 中遇到同样的问题。
【问题讨论】:
标签: c#-4.0 generics inheritance reflection casting