簡體   English   中英

c# 獲取屬性類型是否繼承自一個帶反射的抽象泛型 class

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

我想獲取 class 中包含的所有屬性,其類型繼承自某個抽象和通用 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;
    }

當生成為barChecker<foobar>時,我需要在barChecker<T> class 代碼中放入什么以使其 fooprops 列表包含“value”、“someOtherValue”和“someFloat”的屬性信息?

這是System.Type的擴展方法,它將回答有關 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));
}

這里:

    item.PropertyType is somesortof(foo<>)

必須替換為

    typeof(YourType).IsAssignableFrom(item.PropertyType)

'is' 運算符僅適用於真正的 object 實例,如果您已經有類型引用則不適用。

所以在你的情況下'YourType'是typeof(barchecker < foobar >)?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM