我想获得类中包含的所有属性,该类的类型从某个抽象类和泛型类继承。
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”的属性信息?
这里:item.PropertyType是somesortof(foo <>)必须替换为typeof运算(YourType).IsAssignableFrom(item.PropertyType)
'is'运算符仅适用于真实对象实例,不适用于已经具有类型引用的对象。
所以在您的情况下,'YourType'是typeof(barchecker)吗?