Browse Source

Support passing a dictionary inside an object (#740)

Christian Schwarz 5 years ago
parent
commit
58f8addfe0
2 changed files with 36 additions and 2 deletions
  1. 34 0
      Jint.Tests/Runtime/InteropTests.cs
  2. 2 2
      Jint/Extensions/ReflectionExtensions.cs

+ 34 - 0
Jint.Tests/Runtime/InteropTests.cs

@@ -2044,5 +2044,39 @@ namespace Jint.Tests.Runtime
             Assert.NotNull(c.ToString());
             Assert.Equal((uint)0, c.As<ObjectInstance>().Length);
         }
+
+        class DictionaryWrapper
+        {
+            public IDictionary<string, object> Values { get; set; }
+        }
+
+        class DictionaryTest
+        {
+            public void Test1(IDictionary<string, object> values)
+            {
+                Assert.Equal(1, Convert.ToInt32(values["a"]));
+            }
+
+            public void Test2(DictionaryWrapper dictionaryObject)
+            {
+                Assert.Equal(1, Convert.ToInt32(dictionaryObject.Values["a"]));
+            }
+        }
+
+        [Fact]
+        public void ShouldBeAbleToPassDictionaryToMethod()
+        {
+            var engine = new Engine();
+            engine.SetValue("dictionaryTest", new DictionaryTest());
+            engine.Execute("dictionaryTest.test1({ a: 1 });");
+        }
+
+        [Fact]
+        public void ShouldBeAbleToPassDictionaryInObjectToMethod()
+        {
+            var engine = new Engine();
+            engine.SetValue("dictionaryTest", new DictionaryTest());
+            engine.Execute("dictionaryTest.test2({ values: { a: 1 } });");
+        }
     }
 }

+ 2 - 2
Jint/Extensions/ReflectionExtensions.cs

@@ -11,7 +11,7 @@ namespace Jint.Extensions
             {
                 case MemberTypes.Field:
                     var fieldInfo = (FieldInfo) memberInfo;
-                    if (fieldInfo.FieldType == value?.GetType())
+                    if (value != null && fieldInfo.FieldType.IsAssignableFrom(value.GetType()))
                     {
                         fieldInfo.SetValue(forObject, value);
                     }
@@ -19,7 +19,7 @@ namespace Jint.Extensions
                     break;
                 case MemberTypes.Property:
                     var propertyInfo = (PropertyInfo) memberInfo;
-                    if (propertyInfo.PropertyType == value?.GetType())
+                    if (value != null && propertyInfo.PropertyType.IsAssignableFrom(value.GetType()))
                     {
                         propertyInfo.SetValue(forObject, value);
                     }