任何人都可以解释ASP.NET MVC框架如何从匿名类型参数中检索值,例如Html.ActionLink
,其中表示HTML属性的参数可以作为匿名类型传递。我读过它内部使用Reflection。我正在寻找伪代码或示例来更好地理解。
答案 0 :(得分:2)
它使用RouteValueDictionary珍贵的构造函数,它允许您将匿名对象转换为字典:
class Program
{
static void Main()
{
var anon = new { foo = "foo value", bar = "bar value" };
IDictionary<string, object> values = new RouteValueDictionary(anon);
foreach (var item in values)
{
Console.WriteLine("{0}, {1}", item.Key, item.Value);
}
}
}
就实现而言,您可能总是看一下ASP.NET MVC源代码,但这里是相关部分:
public class RouteValueDictionary : IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable
{
public RouteValueDictionary(object values)
{
this._dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
this.AddValues(values);
}
private void AddValues(object values)
{
if (values != null)
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
{
object obj2 = descriptor.GetValue(values);
this.Add(descriptor.Name, obj2);
}
}
}
...
}
正如您所看到的,它使用TypeDescriptor.GetProperties
方法来检索匿名对象的所有属性及其值。