ScriptCore Fixed CreateInstanceSafe(Type type, params object[] args)

This commit is contained in:
Simon Lübeß
2024-01-01 13:02:15 +01:00
parent 418aa71241
commit e5f2da66a9
+23 -2
View File
@@ -1,4 +1,7 @@
using System; #nullable enable
using System;
using System.Reflection;
namespace GlitchyEngine.Extensions; namespace GlitchyEngine.Extensions;
@@ -7,7 +10,7 @@ public static class ActivatorExtension
/// <summary>Creates an instance of the specified type using that type's default constructor.</summary> /// <summary>Creates an instance of the specified type using that type's default constructor.</summary>
/// <param name="type">The type of object to create.</param> /// <param name="type">The type of object to create.</param>
/// <returns>A reference to the newly created object; or <see langword="null"/> if no instance could be created.</returns> /// <returns>A reference to the newly created object; or <see langword="null"/> if no instance could be created.</returns>
public static object CreateInstanceSafe(Type type) public static object? CreateInstanceSafe(Type type)
{ {
try try
{ {
@@ -28,4 +31,22 @@ public static class ActivatorExtension
return null; return null;
} }
/// <summary>Creates an instance of the specified type using a constructor that matches the given arguments.</summary>
/// <param name="type">The type of object to create.</param>
/// <param name="args">The arguments passed to the constructor</param>
/// <returns>A reference to the newly created object; or <see langword="null"/> if no instance could be created.</returns>
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;
}
} }