2

我们正在将我们的应用程序从 .Net Framework 3.5 升级到 4.0,并且发现 BindingSource 的行为发生了变化。

编码:

bindingSource.DataSource = new Dictionary<int, int>( 0 );

在 .Net Framework 3.5 中不会发出 PositionChanged 事件。但是,当针对 .Net Framework 4.n 编译时,它确实会被触发。在 PositionChanged 事件中检查当前项目时,它包含字典本身。

这是 .Net Framework 4.n 中的错误吗?以下是一些突出显示该行为的测试:

[TestMethod]
public void FW40_WhenBindingToEmptyCollectionThenPositionChangedIsInvoked() {
    Dictionary<int, int> emptyCollection = new Dictionary<int, int>( 0 );

    BindingSource bindingSource = new BindingSource();
    object currentItem = null;

    bindingSource.PositionChanged += ( sender, e ) => {
        currentItem = ( (BindingSource)sender ).CurrencyManager.Current;
    };

    bindingSource.DataSource = emptyCollection;

    Assert.AreEqual<Type>( typeof( Dictionary<int, int> ), currentItem.GetType() );
}

[TestMethod]
public void FW35_WhenBindingToEmptyCollectionThenPositionChangedIsNotInvoked() {
    Dictionary<int, int> emptyCollection = new Dictionary<int, int>( 0 );

    BindingSource bindingSource = new BindingSource();
    object currentItem = null;
    bindingSource.PositionChanged += ( sender, e ) => {
        currentItem = ( (BindingSource)sender ).CurrencyManager.Current;
    };
    bindingSource.DataSource = emptyCollection;

    Assert.IsNull( currentItem );
}

[TestMethod]
public void FWAll_WhenBindingToNonEmptyCollectionThenPositionChangedIsInvokedAndCurrentItemIsKeyValuePair() {
    Dictionary<int, int> noneEmptyCollection = new Dictionary<int, int> { { 1, 1 } };

    BindingSource bindingSource = new BindingSource();
    object currentItem = null;
    bindingSource.PositionChanged += ( sender, e ) => {
        currentItem = ( (BindingSource)sender ).CurrencyManager.Current;
    };
    bindingSource.DataSource = noneEmptyCollection;

    Assert.AreEqual<Type>( typeof( KeyValuePair<int, int> ), currentItem.GetType() );
}
4

0 回答 0