Skip to content

Commit 85d19e0

Browse files
committed
Refined Activator.CreateInstance method
1 parent b0c0afe commit 85d19e0

2 files changed

Lines changed: 43 additions & 3 deletions

File tree

‎CSharp.lua/CoreSystem.Lua/CoreSystem/Exception.lua‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,3 +269,12 @@ define("System.TypeLoadException", {
269269
ctorOfException(this, message or "Failed when load type.", innerException)
270270
end
271271
})
272+
273+
define("System.MissingMethodException", {
274+
__tostring = toString,
275+
__inherits__ = { Exception },
276+
277+
__ctor__ = function(this, message, innerException)
278+
ctorOfException(this, message or "Specified method could not be found.", innerException)
279+
end
280+
})

‎CSharp.lua/CoreSystem.Lua/CoreSystem/Type.lua‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,13 @@ local String = System.String
2121
local Boolean = System.Boolean
2222
local Delegate = System.Delegate
2323
local getClass = System.getClass
24+
local try = System.try
25+
local new = System.new
2426
local arrayFromTable = System.arrayFromTable
2527

2628
local InvalidCastException = System.InvalidCastException
2729
local ArgumentNullException = System.ArgumentNullException
30+
local MissingMethodException = System.MissingMethodException
2831
local TypeLoadException = System.TypeLoadException
2932
local NullReferenceException = System.NullReferenceException
3033

@@ -405,6 +408,34 @@ function System.cast(cls, obj)
405408
end
406409
end
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+
408439
function 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], ...)
423454
end

0 commit comments

Comments
 (0)