2013-05-30 33 views
2

我有许多类都从基类继承 - 这实际上是一个简单的包装器的接口,以允许串行化从而:铸造列表<baseclass>到列表<derivedclass>

public abstract class VoucherRuleBase : IRule{ 
    public abstract bool Save(int nodeID); 
} 

public class ActiveDateRule : VoucherRuleBase{ 
    public DateTime ActiveDateRuleProperty{get;set;} 
    ...etc 
} 

我然后有一个List<VoucherRuleBase>其中包含一些ActiveDateRule对象,或其他派生类的数量。该列表总是充满相同的类型,即。所有的ActiveDateRules或其他派生类之一。

我需要将List转换为列表,因为我试图将列表绑定到网格,但是由于网格只能看到它没有找到任何属性的基类。在运行时,.NET知道'真实'类型,只是在编译时我无法将其转换。这是因为它是不可能的 - 没有每个派生类都有一些构造函数来执行转换?

我搜索过这里确实有类似这样的其他问题,但我没有与任何解决方案运气..

任何帮助非常感谢如初.. 感谢

回答

3

有你试过myList.Cast<BaseClass>

+0

这就是他们已经拥有的。 – Jon

+4

道歉它将列表传递给一个没有重新编译并设置为基类的控件.. doh! both:.OfType ()和.Cast ()工作.. – nat

1

尝试使用as

List<VoucherRuleBase> voucherRules = new List<VoucherRuleBase>(); 
var activeDateRules = voucherRules.Select(x => x as ActiveDateRule); 

你不这样做隐式转换这种方式,你可以通过使用Where和过滤类型不null过滤掉对象。

var activeDateRules = voucherRules.Select(x => x as ActiveDateRule).Where(x => x != null); 
0

这里baseClasses是你的基类的列表。 DerivedClass1是你的老师。

var derivedClasses = baseClasses.Where(item => item.GetType() == typeof(DerivedClass1)).ToList();