BITKit/Src/Core/Extensions/Object.cs

79 lines
2.8 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.DependencyInjection;
using Unity.Mathematics;
namespace BITKit
{
public static partial class Extensions
{
private static readonly ConcurrentDictionary<int,ConcurrentDictionary<int,object>> Services = new();
public static bool QueryComponents<T>(this IServiceProvider self,out T t1) where T : class
{
var id = self.GetHashCode();
var typeId = typeof(T).GetHashCode();
if (Services.GetOrCreate(id).TryGetValue(typeId, out var value) is false)
{
value = self.GetService<T>();
Services.GetOrCreate(id).TryAdd(typeId,value);
}
if (value is null)
{
t1 = null;
return false;
}
t1 = Unsafe.As<T>(value);
return true;
}
public static bool QueryComponents<T,T1> (this IServiceProvider self,out T t1,out T1 t2) where T : class where T1 : class
{
t1 = null;
t2 = null;
if (QueryComponents(self,out t1) is false) return false;
if (QueryComponents(self,out t2) is false) return false;
return true;
}
public static bool QueryComponents<T,T1,T2> (this IServiceProvider self,out T t1,out T1 t2,out T2 t3) where T : class where T1 : class where T2 : class
{
t1 = null;
t2 = null;
t3 = null;
if (QueryComponents(self,out t1) is false) return false;
if (QueryComponents(self,out t2) is false) return false;
if (QueryComponents(self,out t3) is false) return false;
return true;
}
public static bool QueryComponents<T,T1,T2,T3> (this IServiceProvider self,out T t1,out T1 t2,out T2 t3,out T3 t4) where T : class where T1 : class where T2 : class where T3 : class
{
t1 = null;
t2 = null;
t3 = null;
t4 = null;
if (QueryComponents(self,out t1) is false) return false;
if (QueryComponents(self,out t2) is false) return false;
if (QueryComponents(self,out t3) is false) return false;
if (QueryComponents(self,out t4) is false) return false;
return true;
}
public static T IsNull<T>(this T t, Action action)
{
if (t is null)
{
action.Invoke();
}
return t;
}
public static T IsNotNull<T>(this T t, Action<T> action)
{
if (t is not null)
{
action.Invoke(t);
}
return t;
}
}
}