Reputation: 4782
I have the following class structure:
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());
}
}
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>;
}
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?
Upvotes: 0
Views: 132
Reputation: 2284
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>
{
}
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
}
}
Upvotes: 1
Reputation: 391634
You can't.
The compiler cannot verify that what you're doing is legal.
If RelationBaseList
was an interface, you could tag the generic parameter with the out
keyword, to signal that the interface only allows retrieval of data from the object.
However, the way your code is organized, the compiler cannot verify that you're not trying to do this:
case2.Add(new SomeOtherRelationObject());
and the whole point of generics is to make type-safe code.
So no, you cannot do that.
Upvotes: 3