add BindWithRunner

This commit is contained in:
Mikhail 2024-02-25 17:36:33 +08:00
parent b801139e1c
commit a7aa8b0113
4 changed files with 75 additions and 0 deletions

View File

@ -0,0 +1,10 @@
using System;
[AttributeUsage(AttributeTargets.Interface, Inherited = false, AllowMultiple = false)]
sealed class BindWithRunnerAttribute : Attribute
{
public readonly Type runnerType;
public BindWithRunnerAttribute(Type runnerType)
{
this.runnerType = runnerType;
}
}

View File

@ -0,0 +1,37 @@
using DCFApixels.DragonECS.AutoInjections.Internal;
using System;
using System.Reflection;
namespace DCFApixels.DragonECS
{
public static class ProcessRunnerBinder
{
private static MethodInfo _declareRunnerMethod = typeof(EcsPipeline).GetMethod(nameof(EcsPipeline.DeclareRunner));
public static T GetRunnerAuto<T>(this EcsPipeline self) where T : IEcsProcess
{
if(self.TryGetRunner(out T process))
{
return process;
}
Type type = typeof(T);
if (type.TryGetCustomAttribute(out BindWithRunnerAttribute atr))
{
Type runnerType = atr.runnerType;
if (type.IsGenericType)
{
if(runnerType.IsGenericType == false ||
runnerType.IsGenericTypeDefinition == false)
{
Throw.UndefinedException();
}
Type[] genericArguments = type.GetGenericArguments();
runnerType = runnerType.MakeGenericType(genericArguments);
}
return (T)_declareRunnerMethod.MakeGenericMethod(runnerType).Invoke(self, null);
}
Throw.UndefinedException();
return default;
}
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
namespace DCFApixels.DragonECS
{
@ -24,6 +25,11 @@ namespace DCFApixels.DragonECS
//method X has arguments greater than 1.
throw new EcsAutoInjectionException($"{obj.Name} method Arguments != 1");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void UndefinedException()
{
throw new Exception();
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace DCFApixels.DragonECS.AutoInjections.Internal
{
internal static class ReflectionExtenions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryGetCustomAttribute<T>(this Type self, out T attribute) where T : Attribute
{
attribute = self.GetCustomAttribute<T>();
return attribute != null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryGetCustomAttribute<T>(this MemberInfo self, out T attribute) where T : Attribute
{
attribute = self.GetCustomAttribute<T>();
return attribute != null;
}
}
}