C# 4.0 将反射返回的泛型EntitySet强制转换为基类类型的EntitySet
当将反射返回的泛型EntitySet转换为基类类型的EntitySet时,我遇到了一个问题 我的所有Linq2Sql类都继承自名为LinqClassBase的基类,如下所示:C# 4.0 将反射返回的泛型EntitySet强制转换为基类类型的EntitySet,c#-4.0,generics,inheritance,reflection,casting,C# 4.0,Generics,Inheritance,Reflection,Casting,当将反射返回的泛型EntitySet转换为基类类型的EntitySet时,我遇到了一个问题 我的所有Linq2Sql类都继承自名为LinqClassBase的基类,如下所示: public partial class MyTable1 : LinqClassBase 我正在这个基类中编写一个方法,需要遍历所有子EntitySet 我可以检索属性INFO OK作为MatchingEntityProperty // The GetMatchingProperty method (not shown
public partial class MyTable1 : LinqClassBase
我正在这个基类中编写一个方法,需要遍历所有子EntitySet
我可以检索属性INFO OK作为MatchingEntityProperty
// 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);
我尝试将其强制转换为EntitySet,但它返回null:
// This returns null
var matchingSet = matchingProperty.GetValue(this) as EntitySet<LinqClassBase>;
//这将返回null
var matchingSet=matchingProperty.GetValue(this)作为EntitySet;
为什么此强制转换返回null?我猜是因为C#无法将EntitySet转换为EntitySet
如果这个演员不可能,有没有其他的方式来演员
注意:我曾考虑使用另一层反射来调用ToList方法,但随后ConvertAll方法和MylinqBaseClass方法都会遇到同样的问题。我找到了答案。将其转换为IEnumerable可以让我访问ToList方法,而不会导致它返回null
var matchingSet = matchingProperty.GetValue(this) as IEnumerable<LinqClassBase>;
var matchingSet=matchingProperty.GetValue(this)作为IEnumerable;
我仍然不知道为什么铸造它的EntitySet失败了。但至少我有我的解决办法
var matchingSet = matchingProperty.GetValue(this) as IEnumerable<LinqClassBase>;