2012-08-09 77 views
1
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的继承属性。

我该怎么做?我是新来的反思...

+4

看看http://stackoverflow.com/questions/8699053/how-to-check-if-a-class-inherits-another-class-without-instantiating-it你如何检查如果一个类可以转换为另一种类型。 – PhonicUK 2012-08-09 10:39:17

+0

@ PhonicUK你给的参考,使用两种已知的类型来检查,但在我的情况下,派生类的类型是未知的,我试图通过反射来找到它。 – dotNETbeginner 2012-08-09 11:24:36

回答

1

这工程在我的测试应用程序。

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(); 
} 
相关问题