From e5f2da66a9334e986cf760d7257d756e0a6777ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20L=C3=BCbe=C3=9F?= Date: Mon, 1 Jan 2024 13:02:15 +0100 Subject: [PATCH] ScriptCore Fixed CreateInstanceSafe(Type type, params object[] args) --- ScriptCore/Extensions/ActivatorExtension.cs | 25 +++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/ScriptCore/Extensions/ActivatorExtension.cs b/ScriptCore/Extensions/ActivatorExtension.cs index 220623f..596f85b 100644 --- a/ScriptCore/Extensions/ActivatorExtension.cs +++ b/ScriptCore/Extensions/ActivatorExtension.cs @@ -1,4 +1,7 @@ -using System; +#nullable enable + +using System; +using System.Reflection; namespace GlitchyEngine.Extensions; @@ -7,7 +10,7 @@ public static class ActivatorExtension /// Creates an instance of the specified type using that type's default constructor. /// The type of object to create. /// A reference to the newly created object; or if no instance could be created. - public static object CreateInstanceSafe(Type type) + public static object? CreateInstanceSafe(Type type) { try { @@ -28,4 +31,22 @@ public static class ActivatorExtension return null; } + + /// Creates an instance of the specified type using a constructor that matches the given arguments. + /// The type of object to create. + /// The arguments passed to the constructor + /// A reference to the newly created object; or if no instance could be created. + public static object? CreateInstanceSafe(Type type, params object[] args) + { + try + { + return Activator.CreateInstance(type, BindingFlags.Default | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.CreateInstance | BindingFlags.Instance, null, args, null); + } + catch (Exception e) + { + Log.Error($"Failed to create instance of type \"{type}\": {e}"); + } + + return null; + } }