lundi 15 août 2016

Determine if a property is of a generic type and then call a method on that property

In the following code, I'd like to check the properties of the class in the Save method. If any of those properties also descend from BaseClass, I'd like to call their Save method. How do I check to see if a property is of the same base class?

public abstract class BaseClass<T>
{
    public string Id { get; set; }

    public T Find(Id)
    {
      // returns T
    }

    public void Save()
    {
      // save the object
    }
}

public class Name: BaseClass<Name>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Person: BaseClass<Person>
{
    public int Age { get; set; }
    public Name FullName { get; set; }
}

I tried looking at

Type myType = GetType();
PropertyInfo propertyInfo in myType.GetProperties()

but for the FullName property, IsGeneric() was false and I wasn't sure how to get the value and cast it to the right child type.

Thanks.





Aucun commentaire:

Enregistrer un commentaire