[英]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.我想获取 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;
}
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>
?当生成为
barChecker<foobar>
时,我需要在barChecker<T>
class 代码中放入什么以使其 fooprops 列表包含“value”、“someOtherValue”和“someFloat”的属性信息?
Here's an extension method to System.Type
that will answer this and similar questions about inheritance:这是
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));
}
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. 'is' 运算符仅适用于真正的 object 实例,如果您已经有类型引用则不适用。
So in your case 'YourType' is typeof(barchecker< foobar >)?所以在你的情况下'YourType'是typeof(barchecker < foobar >)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.