【发布时间】:2009-01-06 21:48:37
【问题描述】:
我想这也可能被问到创建的类型名称附加到匿名类型多长时间。问题来了:
一个博客有这样的东西:
var anonymousMagic = new {test.UserName};
lblShowText.Text = lblShowText
.Text
.Format("{UserName}", test);
作为一种愿望清单和几种实现方式。由于无聊和冒险,我开始创建一个可以处理此问题的字符串扩展方法:
var anonymousMagic = new {test.UserName, test.UserID};
lblShowText.Text = "{UserName} is user number {UserID}"
.FormatAdvanced(anonymousMagic);
我的想法是从匿名类型中获取属性信息并将其与括号中的字符串匹配。现在有了属性信息来反射,所以我想在类型第一次出现时保存属性信息,这样我就不必再次获取它了。所以我做了这样的事情:
public static String FormatAdvanced(this String stringToFormat, Object source)
{
Dictionary<String, PropertyInfo> info;
Type test;
String typeName;
//
currentType = source.GetType();
typeName = currentType.Name;
//
//info list is a static list for the class holding this method
if (infoList == null)
{
infoList = new Dictionary<String, Dictionary<String, PropertyInfo>>();
}
//
if (infoList.ContainsKey(typeName))
{
info = infoList[typeName];
}
else
{
info = test.GetProperties()
.ToDictionary(item => item.Name);
infoList.Add(typeName, info);
}
//
foreach (var propertyInfoPair in info)
{
String currentKey;
String replacement;
replacement = propertyInfoPair.Value.GetValue(source, null).ToString();
currentKey = propertyInfoPair.Key;
if (stringToFormat.Contains("{" + currentKey + "}"))
{
stringToFormat = stringToFormat
.Replace("{" + currentKey + "}", replacement);
}
}
//
return stringToFormat;
}
现在在测试中,它似乎保留了它为匿名类型创建的名称,以便第二次通过它不会从类型中获取属性信息,而是从字典中获取。
如果多个人同时使用此方法,它在 Session 之类的 Session 中几乎可以工作吗? IE 的类型名称会特定于程序的每个实例吗?还是会比这更糟?什么时候该名称会被丢弃和覆盖?
【问题讨论】:
-
非常皮条客。我无法回答你,但我受到启发将你的一些想法融入我自己的代码中。我使用网络,所以我不必担心会话或匿名类型名称。
-
为什么不改用
Dictionary<Type, Dictionary<String, PropertyInfo>>? -
嗯...因为我知道你会建议它并希望你自我感觉良好?你买那个吗?
-
我可以买那个。它有效,我对自己感觉良好。谢谢。
标签: c# reflection anonymous-types