【问题标题】:Casting a Generic EntitySet returned by Reflection as an EntitySet with a BaseClass Type将反射返回的通用实体集转换为具有基类类型的实体集
【发布时间】: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


    【解决方案1】:

    我想通了。将其转换为 IEnumerable 可以让我访问 ToList 方法,并且不会导致它返回 null。

    var matchingSet = matchingProperty.GetValue(this) as IEnumerable<LinqClassBase>;
    

    我仍然不知道为什么将其转换为 EntitySet 会失败。但至少我有我的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-14
      • 1970-01-01
      • 1970-01-01
      • 2022-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多