@@ -21,10 +21,13 @@ local String = System.String
2121local Boolean = System .Boolean
2222local Delegate = System .Delegate
2323local getClass = System .getClass
24+ local try = System .try
25+ local new = System .new
2426local arrayFromTable = System .arrayFromTable
2527
2628local InvalidCastException = System .InvalidCastException
2729local ArgumentNullException = System .ArgumentNullException
30+ local MissingMethodException = System .MissingMethodException
2831local TypeLoadException = System .TypeLoadException
2932local NullReferenceException = System .NullReferenceException
3033
@@ -405,6 +408,34 @@ function System.cast(cls, obj)
405408 end
406409end
407410
411+ local function tryCallConstructor (cls , ...)
412+ if not cls .__ctor__ then
413+ throw (MissingMethodException (" No matching constructor was found" ))
414+ end
415+ if type (cls .__ctor__ ) == " table" then
416+ local ctorCount = # cls .__ctor__
417+ local instance , ok
418+ local args = {... }
419+ for i = 1 ,ctorCount do
420+ ok = true
421+ System .try (
422+ function ()
423+ instance = new (cls , i , unpack (args ))
424+ end ,
425+ function ()
426+ ok = false
427+ end
428+ )
429+ if ok then
430+ return instance
431+ end
432+ end
433+ throw (MissingMethodException (" No matching constructor was found" ))
434+ else
435+ return cls (... )
436+ end
437+ end
438+
408439function System .CreateInstance (type , ...)
409440 if type == nil then
410441 throw (ArgumentNullException (" type" ))
@@ -415,9 +446,9 @@ function System.CreateInstance(type, ...)
415446 local len = select (" #" , ... )
416447 if len == 1 then
417448 local args = ...
418- if System .isArrayLike (args ) then
419- return type [1 ]( unpack (args ))
449+ if type ( args ) == " table " and System .isArrayLike (args ) then
450+ return tryCallConstructor ( type [1 ], unpack (args ))
420451 end
421452 end
422- return type [1 ]( ... )
453+ return tryCallConstructor ( type [1 ], ... )
423454end
0 commit comments