我有一個類,我想回到我可以定義爲像這樣的屬性基於字符串的各種屬性的值:字典映射字符串性能
[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