.net 使用反射从基类获取子类

.net 使用反射从基类获取子类,.net,inheritance,reflection,.net,Inheritance,Reflection,假设我有以下课堂模型: Class1 -> BaseClass 或 Class1具有 public string Property1 { get; set; } public int Property2 { get; set; } public double Property1 { get; set; } public string Property2 { get; set; } public int Property3 { get; set; } 类2具有 public strin

假设我有以下课堂模型:

Class1 -> BaseClass

Class1具有

public string Property1 { get; set; }
public int Property2 { get; set; }
public double Property1 { get; set; }
public string Property2 { get; set; }
public int Property3 { get; set; }
类2具有

public string Property1 { get; set; }
public int Property2 { get; set; }
public double Property1 { get; set; }
public string Property2 { get; set; }
public int Property3 { get; set; }
我想在基类中创建一个方法,该方法将为实例化的任何子类中的所有属性创建一个哈希。如何使用反射获取子类的属性


由于.Net不允许多重继承,因此我假设只有一个子类(或一行子类)是安全的。

听起来您只是想使用
GetType()
,这将给出当前对象的执行时间类型:

foreach (var property in this.GetType().GetProperties())
{
    var value = property.GetValue(this, null);
    // Whatever
}

当调用
Class1
的实例时,它应该显示
Property1
Property2
,即使代码位于
BaseClass

中,听起来您只是在寻找使用
GetType()
,这将给出当前对象的执行时间类型:

foreach (var property in this.GetType().GetProperties())
{
    var value = property.GetValue(this, null);
    // Whatever
}
当调用
Class1
的实例时,即使代码位于
BaseClass
中,也应显示
Property1
Property2