【发布时间】:2009-05-08 21:38:46
【问题描述】:
我正在为 ASP.NET 编写一个双向绑定控件。我终于把事情搞定了。我正在使用以下代码重新绑定:
private void RebindData()
{
// return if the DataValue wasn't loaded from ViewState
if (DataValue == null)
return;
// extract the values from the two-way binding template
IOrderedDictionary values = new OrderedDictionary();
IBindableTemplate itemTemplate = DataTemplate as IBindableTemplate;
if (itemTemplate != null)
{
foreach (DictionaryEntry entry in itemTemplate.ExtractValues(this))
{
values[entry.Key] = entry.Value;
}
}
// use reflection to push the bound fields back to the datavalue
foreach(var key in values.Keys)
{
var type = typeof(T);
var pi = type.GetProperty(key.ToString());
if (pi != null)
{
pi.SetValue(DataValue, values[key], null);
}
}
}
这适用于像这样的简单情况:
<%# Bind("Name") %>
当我有这样的嵌套绑定语句时,我使用的反射技术不起作用:
<%# Bind("Customer.Name") %>
有没有一种简单的方法可以为这样的嵌套属性使用反射?我应该为此使用递归函数,还是只使用循环?
【问题讨论】:
标签: c# asp.net reflection binding