简体   繁体   中英

How to check list of child is drive from base class

public  class BaseEntity
{
    public int Id { get;  set; }
    public int CreatedBy { get; set; }p
    public DateTime CreatedOn { get; set; }}
}

public class A : BaseEntity
{
    public DateTime Date { get; set;}
    public virtual List<childClassOFA> Contacts { get; set; } //childClassOFA IS Also drive from BaseEntity
}

Type myType = entity.GetType();

foreach (var entityInFo in entity.GetType().GetProperties(System.Reflection.BindingFlags.Public BindingFlags.Instance))
{
    bool isList = entityInFo.PropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(entityInFo.PropertyType);
    if (isList == true)
    {
        var list = entityInFo.GetValue(entity.GetType().GetProperty(entityInFo.Name).GetValue(entity, null)) as List<object>;
        if (list != null) {
            var type = list.Select(a => a.GetType()).FirstOrDefault() ;type.IsSubclassOf(typeof(BaseEntity));
         }
        //do something
    }
}

i need to check that list of childClassOFA drive from BaseEntity or not i have to check weather it belong to the base class or not and also need to get list properties

You can check if the base class of childClassOFA is BaseEntity with is operator . It might look something like this:

if (childClassOFAInstance is BaseEntity)
{
    //your logic here
}

You can also check out as operator, I have issues understanding what you really need to achieve, so maybe it will be better solution for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM