c#获取属性类型是否从一个具有反射的抽象泛型类继承

问题描述 投票:1回答:1

我想获得类中包含的所有属性,该类的类型从某个抽象类和泛型类继承。

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;
    }

[作为barChecker<T>生成时,我需要在barChecker<foobar>类代码中放入什么以使其fooprops列表包含“值”,“ someOtherValue”和“ someFloat”的属性信息?

c# generics properties abstract system.reflection
1个回答
0
投票

这里:item.PropertyType是somesortof(foo <>)必须替换为typeof运算(YourType).IsAssignableFrom(item.PropertyType)

'is'运算符仅适用于真实对象实例,不适用于已经具有类型引用的对象。

所以在您的情况下,'YourType'是typeof(barchecker)吗?

© www.soinside.com 2019 - 2024. All rights reserved.