.NET 4.0中的数据绑定与2.0不同。

4

有人知道为什么.NET 4.0中的数据绑定工作方式不同吗? 即在.NET 4.0中,RelatedPropertyManager.GetItemProperties()返回父对象类型的属性,而不是相关对象类型的属性,如以下示例代码:

using System;
using System.Windows.Forms;

static class Program
{
    static void Main()
    {
        using (Form form = new Form())
        {
            ParentObject parent = new ParentObject();
            BindingManagerBase bindingManager =
                form.BindingContext[parent, "Nested"];
            Console.WriteLine("Has Code1 property: " + 
                (bindingManager.GetItemProperties()["Code1"] != null));
            Console.WriteLine("Has Code2 property: " + 
                (bindingManager.GetItemProperties()["Code2"] != null));

            // .NET 2.0:
            // Has Code1 property: False
            // Has Code2 property: True

            // .NET 4.0:
            // Has Code1 property: True
            // Has Code2 property: False

            Console.ReadKey();
        }
    }

    class ParentObject
    {
        public NestedObject Nested { get; set; }
        public string Code1 { get; set; }
    }

    class NestedObject
    {
        public string Code2 { get; set; }
    }
}

我也在微软社区上提出了问题,但目前还没有得到答复。


永远不要想太多。C#语言引入了许多变化(匿名委托、匿名结构体、匿名方法),那么反射机制也可能会发生改变吗? - Alan Turing
4
.NET 4 中肯定有重大更改。请参见此处:http://msdn.microsoft.com/en-us/library/ee941656.aspx - Daniel Hilgarth
Microsoft Coinnect问题:https://connect.microsoft.com/VisualStudio/feedback/details/688427/binding-to-a-nested-property-does-not-work-in-net-4-again#details - Mykola Kovalchuk
3个回答

3
问题的原因在于PropertyManager.GetItemProperties(PropertyDescriptor[] list accessors)方法中,该方法是从RelatedPropertyManager中调用的。 在.NET 4中,listAccessors参数被忽略了。
internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
    if (this.dataSource == null)
        return new PropertyDescriptorCollection((PropertyDescriptor[]) null);
    else
        return TypeDescriptor.GetProperties(this.dataSource);

}

在.NET 2.0中,它是这样的:
internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
    return ListBindingHelper.GetListItemProperties(this.dataSource, listAccessors);
}

但我不确定这是一个错误还是功能上的有意变更。

2

在主要版本发布之间发生变化(即使是重要的变化)并不罕见。在这种情况下,框架相差两个主要版本。

此外,您还可以注意到,仅安装了.NET 4.0 Framework的客户端将无法运行.NET 2.0(或3.x)应用程序,而安装了3.x的客户端则能够运行2.0应用程序。.NET 4.0是一个巨大的跳跃,包括@Daniel提到的破坏性变化。


1
嗯,你提到的最后一件事情背后的原因是.NET 4带来了一个新的运行时,而.NET 3没有。 - Joey

1
这样的问题总是引发一个问题:这是一个错误还是一个特性?我几乎无法想象这是有意行为,因为在 .net 3.5 (2.0) 中,当你执行 BindingManagerBase bindingManager = form.BindingContext[parent](不带 "Nested")时,你会得到 4.0 的结果。
当 dataMember 参数没有效果时,为什么 BindingContext 会有一个 Item[dataSource, dataMember] 属性?请随时告知我们有关 Microsoft 问题的信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接