[英]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");
}
I want to know if the member of class Q (ie., Class B) is compatible with Class A by Reflection 我想通过反射了解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)
//{}
}
}
and then I want to iterate through the inherited properties of B.. 然后我要遍历B.的继承属性。
How do I do this? 我该怎么做呢? I am new to reflection... 我是新来的反思...
This works in my test app. 这适用于我的测试应用。
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.