Kaynağa Gözat

Allow setting Nullable properties on POCO instances

Fixes #313

System.Convert.ChangeType does not work with Nullable types, so special
handling must be added before the call in DefaultTypeCoverter.cs
linusconcepcion 9 yıl önce
ebeveyn
işleme
c10a6a1657

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

@@ -554,6 +554,30 @@ namespace Jint.Tests.Runtime
             ");
         }
 
+        private class TestClass
+        {
+            public int? NullableInt { get; set; }
+            public DateTime? NullableDate { get; set; }
+            public bool? NullableBool { get; set; }
+        }
+
+        [Fact]
+        public void CanSetNullablePropertiesOnPocos()
+        {
+            var instance = new TestClass();
+            _engine.SetValue("instance", instance);
+
+            RunTest(@"
+                instance.NullableInt = 2;
+                instance.NullableDate = new Date();
+                instance.NullableBool = true;
+
+                assert(instance.NullableInt===2);
+                assert(instance.NullableDate!=null);
+                assert(instance.NullableBool===true);
+            ");
+        }
+
         [Fact]
         public void ShouldConvertArrayToArrayInstance()
         {

+ 3 - 0
Jint/Runtime/Interop/DefaultTypeConverter.cs

@@ -184,6 +184,9 @@ namespace Jint.Runtime.Interop
                 return result;
             }
 
+            if (type.IsGenericType && type.GetGenericTypeDefinition()==typeof(Nullable<>))
+                type = Nullable.GetUnderlyingType(type);
+
             return System.Convert.ChangeType(value, type, formatProvider);
         }