![](/img/trans.png)
[英]How to best check for List type on reflection and iterate over its members
[英]check if the type is compatible with parent and then iterate through its properties by reflection
class A
{
public string proprt1 { get; set; }
public string proprt2 { get; set; }
public A(string p1,string p2)
{
proprt1 = p1;
proprt2 = p2;
}
}
class B : A
{
public B(string p1,string p2):base(p1,p2)
{
}
}
class Q
{
public B b = new B("a","b");
}
我想通过反射了解Q类的成员(即B类)是否与A类兼容
private void someMethod()
{
Q q = new Q();
Type type = q.GetType();
foreach (FieldInfo t in type.GetFields())
{
//I am stuck here
//if (t.GetType() is A)
//{}
}
}
然后我要遍历B.的继承属性。
我该怎么做呢? 我是新来的反思...
这适用于我的测试应用。
static void Main(string[] args) {
Q q = new Q();
Type type = q.GetType();
Type aType = typeof(A);
foreach (var fi in type.GetFields()) {
object fieldValue = fi.GetValue(q);
var fieldType = fi.FieldType;
while (fieldType != aType && fieldType != null) {
fieldType = fieldType.BaseType;
}
if (fieldType == aType) {
foreach (var pi in fieldType.GetProperties()) {
Console.WriteLine("Property {0} = {1}", pi.Name, pi.GetValue(fieldValue, null));
}
}
Console.WriteLine();
}
Console.ReadLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.