投射到通用基本类型 [英] Casting to a generic base type

查看:181
本文介绍了投射到通用基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类结构:

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和I想要将其转换为 RelationBaseList 。很遗憾,我只能将其转换为 RelationBaseList< RelationURL>

Via reflection, I get an instance of RelationURLList and I want to cast it to RelationBaseList<RelationBase>. Unfortunately, I can only cast it to 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为null。因为我不想投射到每个可能的派生类从RelationBase,我想使用第二个cast(cast2)。

In cast1, I have the expected object, but cast2 is null. As I don't want to cast to each possibly derived class from RelationBase, I want to use the second cast (cast2). Any idea, how I can get the object, without casting to each single derived type?

推荐答案

你想要什么? > do 与RelationBaseList.Collection?

What do you want to do with the RelationBaseList.Collection?

使用接口可能是一个可能的解决方案,如果你只想访问集合的值,他们:

Using an interface could be a possible solution, if you only want to access the values of the Collection rather than setting them:

public interface IRelationBaseList
{
    IEnumerable<RelationBase> Collection { get; }
}

public class RelationBaseList<T> : IRelationBaseList where T : RelationBase
{
    IEnumerable<RelationBase> IRelationBaseList.Collection
    {
        get { return Collection; }
    }
    public List<T> Collection { get; set; }
}

public class RelationURLList : RelationBaseList<RelationURL>
{

}


$ b



So you can do:

RefTest obj = new RefTest();
PropertyInfo[] props = obj.GetType().GetProperties();
foreach (PropertyInfo prop in props)
{
    object PropertyValue = prop.GetValue(obj, null);

    var relationBaseList = PropertyValue as IRelationBaseList;
    foreach (var relationBase in relationBaseList.Collection)
    { 
        // do something with it
    }
}

这篇关于投射到通用基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆