我有一个类,我想回到我可以定义为像这样的属性基于字符串的各种属性的值:字典映射字符串性能
[FieldName("data_bus")]
public string Databus
{
get { return _record.Databus; }
}
所以像我的字典控股:
private static readonly IDictionary<string, Func<string>> PropertyMap;
这是这里初始化:
static MyClass()
{
PropertyMap = new Dictionary<string, Func<string>>();
var myType = typeof(ArisingViewModel);
foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.GetGetMethod() != null)
{
var attr = propertyInfo.GetCustomAttribute<FieldNameAttribute>();
if (attr == null)
continue;
PropertyInfo info = propertyInfo;
PropertyMap.Add(attr.FieldName,() => info.Name);
// Not sure what I'm doing here.
}
}
}
不知怎么调用阿龙g行:
public static object GetPropertyValue(object obj, string field)
{
Func<string> prop;
PropertyMap.TryGetValue(field, out prop);
// return
}
任何人都可以告诉我如何设置它?我不确定我是否正确理解Func的工作原理。
谢谢,这是一个绝对完美的答案。 – jimbo 2014-10-29 11:26:31