Просмотр исходного кода

Add new constructor to AvaloniaDictionary and include unit tests #17311 (#17312)

* Give AvaloniaDictionary new .ctor and add Tests for it
#17311

* AvaloniaDictionary accept IDictionary as init collection

---------

Co-authored-by: Julien Lebosquain <[email protected]>
Yaroslav 9 месяцев назад
Родитель
Сommit
58dacb051c

+ 15 - 0
src/Avalonia.Base/Collections/AvaloniaDictionary.cs

@@ -34,6 +34,21 @@ namespace Avalonia.Collections
             _inner = new Dictionary<TKey, TValue>(capacity);
         }
 
+        /// <summary>
+        /// Initializes a new instance of the <see cref="AvaloniaDictionary{TKey, TValue}"/> class using an IDictionary.
+        /// </summary>
+        public AvaloniaDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey>? comparer = null)
+        {
+            if (dictionary != null)
+            {
+                _inner = new Dictionary<TKey, TValue>(dictionary, comparer ?? EqualityComparer<TKey>.Default);
+            }
+            else
+            {
+                throw new ArgumentNullException(nameof(dictionary));
+            }
+        }
+
         /// <summary>
         /// Occurs when the collection changes.
         /// </summary>

+ 31 - 0
tests/Avalonia.Base.UnitTests/Collections/AvaloniaDictionaryTests.cs

@@ -1,8 +1,10 @@
 using System;
 using System.Collections.Generic;
 using System.Collections.Specialized;
+
 using Avalonia.Collections;
 using Avalonia.Data.Core;
+
 using Xunit;
 
 namespace Avalonia.Base.UnitTests.Collections
@@ -156,5 +158,34 @@ namespace Avalonia.Base.UnitTests.Collections
 
             Assert.Equal(new[] { "Count", CommonPropertyNames.IndexerName }, tracker.Names);
         }
+
+        [Fact]
+        public void Constructor_Should_Throw_ArgumentNullException_When_Collection_Is_Null()
+        {
+            Assert.Throws<ArgumentNullException>(() =>
+            {
+                var target = new AvaloniaDictionary<string, string>(null, null);
+            });
+        }
+
+
+        [Fact]
+        public void Constructor_Should_Initialize_With_Provided_Collection()
+        {
+            var initialCollection = new Dictionary<string, string>
+            {
+                { "key1", "value1" },
+                { "key2", "value2" }
+            };
+
+            var target = new AvaloniaDictionary<string, string>(initialCollection, null);
+
+            Assert.Equal(2, target.Count);
+            Assert.Equal("value1", target["key1"]);
+            Assert.Equal("value2", target["key2"]);
+        }
+
+
+
     }
 }