【问题标题】:c# Get if property type inherits from one abstract generic class with reflectionc# 获取属性类型是否继承自一个带有反射的抽象泛型类
【发布时间】:2020-01-30 23:29:27
【问题描述】:

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

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&lt;foobar&gt; 时,我需要在barChecker&lt;T&gt; 类代码中添加什么以使其 fooprops 列表包含“value”、“someOtherValue”和“someFloat”的属性信息?

【问题讨论】:

    标签: c# generics properties abstract system.reflection


    【解决方案1】:

    这是System.Type 的扩展方法,可以回答这个问题和类似的关于继承的问题:

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

    【讨论】:

      【解决方案2】:

      这里是:

          item.PropertyType is somesortof(foo<>)
      

      必须替换为

          typeof(YourType).IsAssignableFrom(item.PropertyType)
      

      “is”运算符仅适用于真实对象实例,如果您已经有类型引用,则不适用。

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

      【讨论】:

      • 问题是typeof(foo&lt;&gt;) 类型的引用不能从typeof(foo&lt;int&gt;) 分配。我看不出像foo&lt;&gt; 这样的未封闭泛型类型在这里有什么用处。
      猜你喜欢
      • 2014-12-03
      • 2021-07-05
      • 2017-02-23
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多