fix: refactor, wrap getordefault and invoke safely

This commit is contained in:
2026-06-18 17:20:09 -03:00
parent d5fda4be69
commit d79017ed6a
+7 -23
View File
@@ -1,8 +1,13 @@
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Objects; using CUE4Parse.UE4.Assets.Objects;
using System.Reflection; using System.Reflection;
public static class StructMapper public static class StructMapper
{ {
private static readonly MethodInfo _getOrDefaultMethod = typeof(AbstractPropertyHolder)
.GetMethods()
.First(m => m.Name == "GetOrDefault" && m.GetGenericArguments().Length == 1);
public static T MapToStruct<T>(this FStructFallback fallback) where T : struct public static T MapToStruct<T>(this FStructFallback fallback) where T : struct
{ {
object result = new T(); object result = new T();
@@ -10,38 +15,17 @@ public static class StructMapper
foreach (var field in fields) foreach (var field in fields)
{ {
if (field.FieldType.IsArray)
{
var prop = fallback.Properties.FirstOrDefault(p => p.Name.Text == field.Name);
if (prop?.Tag != null)
{
var value = prop.Tag.GetValue(field.FieldType);
field.SetValue(result, value);
}
continue;
}
try try
{ {
var method = typeof(CUE4Parse.UE4.Assets.Exports.AbstractPropertyHolder) var genericMethod = _getOrDefaultMethod.MakeGenericMethod(field.FieldType);
.GetMethods()
.FirstOrDefault(m => m.Name == "GetOrDefault" && m.GetGenericArguments().Length == 1);
if (method != null)
{
var genericMethod = method.MakeGenericMethod(field.FieldType);
var value = genericMethod.Invoke(fallback, new object[] { field.Name, null!, StringComparison.Ordinal }); var value = genericMethod.Invoke(fallback, new object[] { field.Name, null!, StringComparison.Ordinal });
if (value != null) if (value != null)
{
field.SetValue(result, value); field.SetValue(result, value);
} }
}
}
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Mapping failed for {field.Name}: {ex.Message}"); Console.WriteLine($"Mapping failed for {field.Name}: {ex.InnerException?.Message ?? ex.Message}");
} }
} }