我是一名有用的助手,可以翻译文本。
我目前有一个名为'ArisingViewModel'的类,其中包含约20-30个属性,在生成各种数据时将检查这些属性10,000多次。
最初,我有一个从XML字符串中检索出现属性值的方法,类似于:
public object GetArisingPropertyValue(string propertyName)
{
switch (propertyName)
{
case "name_1":
return Name1;
case "another_name":
return AnotherName;
// etc.
}
}
但是为了更方便地更新和处理项目中的其他部分,这被改成使用属性字典。因此,我设置了如下的属性字典:
private static readonly IDictionary<string, string> PropertyMap;
static ArisingViewModel()
{
PropertyMap = new Dictionary<string, 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;
PropertyMap.Add(attr.FieldName, propertyInfo.Name);
}
}
}
我会像这样为任何相关的属性应用属性:
[FieldName("name_1")]
public string Name1
{
get
{
return _arisingRecord.Name1;
}
}
然后使用以下方法查找属性名称/值:
public static string GetPropertyMap(string groupingField)
{
string propName;
PropertyMap.TryGetValue(groupingField, out propName);
return propName; //will return null in case map not found.
}
public static object GetPropertyValue(object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
我的问题是,我发现使用旧的switch语句处理速度要快得多(使用一个非常简单的计时器类来测量系统花费的时间 - 大约20秒对比大约25秒)。
有人能建议我做错了什么,或者有任何改进当前代码的方法吗?