简体   繁体   中英

c# Get if property type inherits from one abstract generic class with reflection

I would like to get all of the properties contained in a class whose types inherit from a certain abstract and generic class.

public abstract class foo<T> { }

public class fooInt_Indexed : foo<int> { }
public class fooInt_Not_Indexed : foo<int> { }
public class fooString_Compressed : foo<string> { }
public class fooString_Indexed : foo<string> { }
public class fooFloat : foo<float> { }

public abstract class bar
{

}

public class foobar : bar
{
    public fooInt_Indexed value { get; set; }
    public fooInt_Not_Indexed someOtherValue { get; set; }
    public fooFloat someFloat { get; set; }
    public otherData<int> {get; set; }
}

public class barChecker<T> where T : bar
{
    public List<PropertyInfo> fooprops = new List<PropertyInfo>();
    public static barChecker<T> Generator()
    {
        var @new = new barChecker<T>();
        foreach (var item in typeof(T).GetProperties())
        {
            if (item.PropertyType is somesortof(foo<>)) @new.fooprops.Add(item);
        }
        return @new;
    }

What do I need to put inside the barChecker<T> class code to make its fooprops list contain the property infos of "value","someOtherValue" and "someFloat" when generated as a barChecker<foobar> ?

Here's an extension method to System.Type that will answer this and similar questions about inheritance:

public static class TypeExtensions
{
    public static bool InheritsFrom(this Type t, Type baseType)
    {
        if (t.BaseType == null)
        {
            return false;
        }
        else if (t == baseType)
        {
            return true;
        }
        else if (t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition().InheritsFrom(baseType))
        {
            return true;
        }
        else if (t.BaseType.InheritsFrom(baseType))
        {
            return true;
        }
        return false;
    }

    public static bool InheritsFrom<TBaseType>(this Type t)
        => t.InheritsFrom(typeof(TBaseType));
}

This here:

    item.PropertyType is somesortof(foo<>)

Has to be replaced with

    typeof(YourType).IsAssignableFrom(item.PropertyType)

The 'is' operator is only for real object instances, not if you already have a Type-Reference.

So in your case 'YourType' is typeof(barchecker< foobar >)?

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