com.alicizax.unity.framework/Runtime/UI/Constant/Em.cs
2025-09-05 19:46:30 +08:00

32 lines
966 B
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
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($"类型 {type.Name} 缺少公共无参构造函数");
}
// 构建表达式树new T()
var newExpr = Expression.New(ctor);
var lambda = Expression.Lambda<Func<object>>(newExpr);
constructor = lambda.Compile();
// 缓存委托
_constructorCache[type] = constructor;
}
return constructor();
}
}