【问题标题】:How do I use reflection to get the nested property如何使用反射来获取嵌套属性
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 我研究了许多使用内置 ASP.NET 双向绑定的不同方法,我的方法与 FormView 非常相似,但我希望 DataSource 是单个项目,而不是 IEnumerable .
    • 抱歉...不清楚。我正在考虑使用已经支持子属性命名约定的内置 DataBinder.Eval 方法。但是,要解决 IEnumerable 问题 - 您不必直接绑定到集合。您可以直接一个对象,然后通过名称绑定到该对象的属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    相关资源
    最近更新 更多