2
0
Эх сурвалжийг харах

Add support for constructors with default parameters (#1383)

Christian Schwarz 2 жил өмнө
parent
commit
b5ce1b4844

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

@@ -3122,5 +3122,23 @@ try {
             var ex2 = Assert.Throws<JavaScriptException>(() => engineNoWrite.Execute("delete data['a'];"));
             Assert.Equal("Cannot delete property 'a' of System.Collections.Generic.Dictionary`2[System.String,System.Int32]", ex2.Message);
         }
+
+        public record RecordTestClass(object Value = null);
+
+        public class RecordTestClassContext
+        {
+            public object Method(RecordTestClass recordTest)
+            {
+                return recordTest.Value;
+            }
+        }
+
+        [Fact]
+        public void CanConstructOptionalRecordClass()
+        {
+            _engine.SetValue("Context", new RecordTestClassContext());
+            Assert.Equal(null, _engine.Evaluate("Context.method({});").ToObject());
+            Assert.Equal(5, _engine.Evaluate("Context.method({ value: 5 });").AsInteger());
+        }
     }
 }

+ 17 - 1
Jint/Runtime/Interop/DefaultTypeConverter.cs

@@ -134,6 +134,8 @@ namespace Jint.Runtime.Interop
                     ExceptionHelper.ThrowArgumentException("No valid constructors found");
                 }
 
+                var constructorParameters = Array.Empty<object>();
+
                 // reference types - return null if no valid constructor is found
                 if (!type.IsValueType)
                 {
@@ -147,13 +149,27 @@ namespace Jint.Runtime.Interop
                         }
                     }
 
+                    if (!found)
+                    {
+                        foreach (var constructor in constructors)
+                        {
+                            var parameterInfos = constructor.GetParameters();
+                            if (parameterInfos.All(p => p.IsOptional) && constructor.IsPublic)
+                            {
+                                constructorParameters = new object[parameterInfos.Length];
+                                found = true;
+                                break;
+                            }
+                        }
+                    }
+
                     if (!found)
                     {
                         ExceptionHelper.ThrowArgumentException("No valid constructors found");
                     }
                 }
 
-                var obj = Activator.CreateInstance(type, System.Array.Empty<object>());
+                var obj = Activator.CreateInstance(type, constructorParameters);
 
                 var members = type.GetMembers();
                 foreach (var member in members)