![](/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.