com.alicizax.unity.framework/Runtime/UI/Constant/Em.cs

33 lines
1.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Cysharp.Text;
public static class InstanceFactory
{
private static readonly Dictionary<Type, Func<object>> _constructorCache = new();
public static object CreateInstanceOptimized(Type type)
{
if (!_constructorCache.TryGetValue(type, out var constructor))
{
// 楠岃瘉鏄惁瀛樺湪鍏叡鏃犲弬鏋勯€犲嚱鏁?
var ctor = type.GetConstructor(Type.EmptyTypes);
if (ctor == null)
{
throw new MissingMethodException(ZString.Format("Type {0} missing public parameterless constructor", type.Name));
}
// 鏋勫缓琛ㄨ揪寮忔爲锛歯ew T()
var newExpr = Expression.New(ctor);
var lambda = Expression.Lambda<Func<object>>(newExpr);
constructor = lambda.Compile();
// 缂撳瓨濮旀墭
_constructorCache[type] = constructor;
}
return constructor();
}
}