Browse Source

Fix a error that occurs when creating an instance of value type without parameters

Andrey Taritsyn 9 years ago
parent
commit
d9469b6e6a
2 changed files with 20 additions and 2 deletions
  1. 10 1
      Jint.Tests/Runtime/InteropTests.cs
  2. 10 1
      Jint/Runtime/Interop/TypeReference.cs

+ 10 - 1
Jint.Tests/Runtime/InteropTests.cs

@@ -818,7 +818,7 @@ namespace Jint.Tests.Runtime
         }
         }
 
 
         [Fact]
         [Fact]
-        public void ShouldConstructWithParameters()
+        public void ShouldConstructReferenceTypeWithParameters()
         {
         {
             RunTest(@"
             RunTest(@"
                 var Shapes = importNamespace('Shapes');
                 var Shapes = importNamespace('Shapes');
@@ -828,6 +828,15 @@ namespace Jint.Tests.Runtime
             ");
             ");
         }
         }
 
 
+        [Fact]
+        public void ShouldConstructValueTypeWithoutParameters()
+        {
+            RunTest(@"
+                var guid = new System.Guid();
+                assert('00000000-0000-0000-0000-000000000000' === guid.ToString());
+            ");
+        }
+
         [Fact]
         [Fact]
         public void ShouldInvokeAFunctionByName()
         public void ShouldInvokeAFunctionByName()
         {
         {

+ 10 - 1
Jint/Runtime/Interop/TypeReference.cs

@@ -44,6 +44,14 @@ namespace Jint.Runtime.Interop
 
 
         public ObjectInstance Construct(JsValue[] arguments)
         public ObjectInstance Construct(JsValue[] arguments)
         {
         {
+            if (arguments.Length == 0 && Type.IsValueType)
+            {
+                var instance = Activator.CreateInstance(Type);
+                var result = TypeConverter.ToObject(Engine, JsValue.FromObject(Engine, instance));
+
+                return result;
+            }
+
             var constructors = Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
             var constructors = Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
             
             
             var methods = TypeConverter.FindBestMatch(Engine, constructors, arguments).ToList();
             var methods = TypeConverter.FindBestMatch(Engine, constructors, arguments).ToList();
@@ -71,7 +79,8 @@ namespace Jint.Runtime.Interop
                     }
                     }
 
 
                     var constructor = (ConstructorInfo)method;
                     var constructor = (ConstructorInfo)method;
-                    var result = TypeConverter.ToObject(Engine, JsValue.FromObject(Engine, constructor.Invoke(parameters.ToArray())));
+                    var instance = constructor.Invoke(parameters.ToArray());
+                    var result = TypeConverter.ToObject(Engine, JsValue.FromObject(Engine, instance));
 
 
                     // todo: cache method info
                     // todo: cache method info