动态获取 class 组件中 属性 的值

Get value of a property in a component in a class dynamically

我有以下class

public class Statement
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
    public Narrative Narrative { get; set; }
}

public class Narrative
{
    public string Narrative1 { get; set; }
    public string Narrative2 { get; set; }
    public string Narrative3 { get; set; }
}

我想动态获取 Narrative1 属性。谁能帮助实现这一目标?

我知道如何使用 reflection.And 在 class 中获取 a 属性 名称的值,这里是相同的代码。

public static object ReflectPropertyValue(object source, string property)
{
    return source.GetType().GetProperty(property).GetValue(source,null);
}

任何人都可以帮助如何在另一个 属性 中获取 属性 的值吗?

谢谢

假设您有一个 Statement 对象,您可以在您的方法中使用 属性 Narrative 属性 作为 source。例如:

var statement = new Statement();
// fill properties... change object's state

// get the reference of narrative object
object narrative = ReflectPropertyValue(statement, "Narrative");

// get the value and safe cast it to string
var narrative1Value = ReflectPropertyValue(narrative, "Narrative1") as string;