feat: added more methods for TypeFactory
This commit is contained in:
parent
6e5b805803
commit
0184d1758c
@ -1,21 +1,34 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
namespace Syntriax.Engine.Core.Factory;
|
namespace Syntriax.Engine.Core.Factory;
|
||||||
|
|
||||||
public static class TypeFactory
|
public static class TypeFactory
|
||||||
{
|
{
|
||||||
public static T Get<T>(params object?[]? args) where T : class
|
public static T Get<T>(params object?[]? args) where T : class => (T)Get(typeof(T), args);
|
||||||
|
public static object Get(string fullName, params object?[]? args) => Get(GetType(fullName), args);
|
||||||
|
public static object Get(Type type, params object?[]? args)
|
||||||
{
|
{
|
||||||
T? result;
|
object? result;
|
||||||
|
|
||||||
if (args is not null && args.Length != 0)
|
if (args is not null && args.Length != 0)
|
||||||
result = Activator.CreateInstance(typeof(T), args) as T;
|
result = Activator.CreateInstance(type, args);
|
||||||
else
|
else
|
||||||
result = Activator.CreateInstance(typeof(T)) as T;
|
result = Activator.CreateInstance(type);
|
||||||
|
|
||||||
if (result is null)
|
if (result is null)
|
||||||
throw new Exception($"{typeof(T).Name} of type {typeof(T).Name} could not be created.");
|
throw new Exception($"Type {type.Name} could not be created.");
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static Type GetType(string fullName)
|
||||||
|
{
|
||||||
|
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
|
||||||
|
if (assembly.GetTypes().FirstOrDefault(t => t.FullName?.CompareTo(fullName) == 0) is Type type)
|
||||||
|
return type;
|
||||||
|
|
||||||
|
throw new Exception($"Type {fullName} could not be found in the current domain.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user