【发布时间】:2013-12-17 11:10:43
【问题描述】:
我有以下类结构:
public class RelationBase : Entity
{
}
public class RelationURL : RelationBase
{
}
public class RelationBaseList<T> where T: RelationBase
{
public List<T> Collection { get; set; }
}
public class RelationURLList : RelationBaseList<RelationURL>
{
}
public class RefTest
{
public RelationURLList urlList { get; set; }
public RefTest()
{
urlList = new RelationURList();
urlList.Collection = new List<RelationUR>();
urlList.Collection.Add(new RelationUR());
}
}
通过反射,我得到了一个 RelationURLList 实例,我想将它转换为 RelationBaseList<RelationBase>。不幸的是,我只能将其转换为RelationBaseList<RelationURL>
RefTest obj = new RefTest();
PropertyInfo[] props = obj.GetType().GetProperties();
foreach (PropertyInfo prop in props)
{
object PropertyValue = prop.GetValue(obj, null);
object cast1 = PropertyValue as RelationBaseList<RelationURL>;
object cast2 = PropertyValue as RelationBaseList<RelationBase>;
}
在 cast1 中,我有预期的对象,但 cast2 为空。由于我不想从 RelationBase 转换为每个可能的派生类,我想使用第二个转换 (cast2)。任何想法,我如何获取对象,而不转换为每个派生类型?
【问题讨论】:
标签: c# generics reflection casting