假设我有一个LunchBox类,其中包含FreezerPack的属性,该属性具有Name属性。
public class LunchBox
{
public FreezerPack FreezerPack { get; set; }
}
public class FreezerPack
{
public string Name { get; set; }
}
使用反射,我可以这样得到FreezerPack:
var lunchBox = new LunchBox
{
FreezerPack = new FreezerPack
{
Name = "I'm so cool"
}
};
var freezerPack = typeof(LunchBox)
.GetProperty("FreezerPack")
.GetValue(lunchBox, null);
但是我怎么能从LunchBox中的FreezerPack获取Name,当时我只有LunchBox为T和一个属性路径为“FreezerPack.Name”的字符串? .GetProperty("FreezerPack.Name")
似乎无法解决问题。
答案 0 :(得分:2)
不,您需要反思FreezerPack
:
var lunchBox = new LunchBox() { FreezerPack = new FreezerPack() { Name = "I'm so cool" } };
var freezerPack = typeof(LunchBox).GetProperty("FreezerPack").GetValue(lunchBox, null);
var freezerPackName = freezerPack.GetType().GetProperty("Name").GetValue(freezerPack, null);
Console.WriteLine(freezerPackName);
答案 1 :(得分:0)
dynamic
可能有意义:
dynamic lunchBox = new LunchBox() { FreezerPack = new FreezerPack() { Name = "I'm so cool" } };
string name = lunchBox.FreezerPack.Name;