代码之家  ›  专栏  ›  技术社区  ›  bendewey

如何使用反射获取嵌套属性

  •  0
  • bendewey  · 技术社区  · 17 年前

    我正在为ASP.NET编写Twoway绑定控件。我终于把事情做好了。我正在使用以下代码重新绑定:

    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") %>
    

    对于这样的嵌套属性,是否有一种简单的使用反射的方法?我应该对此使用递归函数,还是只使用循环?

    1 回复  |  直到 17 年前
        1
  •  1
  •   Paul Alexander    17 年前

    为什么不使用已经支持此功能的ASP.NET DataBinder?

    推荐文章