vendredi 27 mai 2016

Check if property inherit from type [duplicate]

This question already has an answer here:

I have:

class ViewModelBaseExtended<T> : NotifyPropertyChange, INotifyDataErrorInfo where T : ViewModelBaseExtended<T>
{

}

class ClassA : ViewModelBaseExtended<ClassA>
{
    public ClassB { get; set; }

    public ClassC { get; set; }
}

class ClassB : ViewModelBaseExtended<ClassB>
{

}

class ClassC
{

}

In constructor of ViewModelBaseExtended<T> i want to get all properties of this class and run some method with each property that inherit from ViewModelBaseExtended<T>

So when i instantiate ClassA it must find that public ClassB { get; set; } is inherit from ViewModelBaseExtended<T> and run some code. And ignore ClassC property because its not inherit from ViewModelBaseExtended<T>.

I try it like:

PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (PropertyInfo p in properties)
    {
        var propertyType = p.PropertyType;

        if(typeof(propertyType).IsAssignableFrom(ViewModelBaseExtended<>))
        {
            //SUCCESS, do something
        }
        //else ignore this property
    }

Any ideas?





Aucun commentaire:

Enregistrer un commentaire