我正在尝试访问以下类的成员值:
public class EditorialDateFormat
{
public string en; <------ TRYING TO GET ITS VALUE
public string fr; <------ OR THIS VALUE
public string Default;<-- OR THIS ONE
}
public class Params
{
public string Template;
public string MainTagID;
public string[] NavigationFilters;
public EditorialDateFormat EditorialDateFormat;
}
public class Site
{
public string Name;
public string CreationFolder;
public Params Params;
public string[] Feed;
public string Endpoint;
public string[] TargetDatabases;
}
我可以轻松地做到:
site.Params.EditorialDateFormat.en
(例如),但“ en”字符串实际上存储在变量中。
我尝试了以下代码:
// Myvariable contains "en"
object c = GetPropValue(site.Params.EditorialDateFormat, MyVariable);
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetMember(propName);
}
但是它返回了一个MemberInfo
对象,没有成员 value
我将不胜感激!
预先感谢
答案 0 :(得分:4)
您想读取 field (公共实例字段的值),这就是我们放入GetField
的原因:
//TODO: rename the method: it doesn't read property (Prop)
public static object GetPropValue(object src, string propName) {
return src
.GetType()
.GetField(propName, BindingFlags.Public | BindingFlags.Instance)
.GetValue(src);
}