fix: refactor, wrap getordefault and invoke safely
This commit is contained in:
+10
-26
@@ -1,8 +1,13 @@
|
||||
using CUE4Parse.UE4.Assets.Exports;
|
||||
using CUE4Parse.UE4.Assets.Objects;
|
||||
using System.Reflection;
|
||||
|
||||
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
|
||||
{
|
||||
object result = new T();
|
||||
@@ -10,38 +15,17 @@ public static class StructMapper
|
||||
|
||||
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
|
||||
{
|
||||
var method = typeof(CUE4Parse.UE4.Assets.Exports.AbstractPropertyHolder)
|
||||
.GetMethods()
|
||||
.FirstOrDefault(m => m.Name == "GetOrDefault" && m.GetGenericArguments().Length == 1);
|
||||
var genericMethod = _getOrDefaultMethod.MakeGenericMethod(field.FieldType);
|
||||
var value = genericMethod.Invoke(fallback, new object[] { field.Name, null!, StringComparison.Ordinal });
|
||||
|
||||
if (method != null)
|
||||
{
|
||||
var genericMethod = method.MakeGenericMethod(field.FieldType);
|
||||
|
||||
var value = genericMethod.Invoke(fallback, new object[] { field.Name, null!, StringComparison.Ordinal });
|
||||
|
||||
if (value != null)
|
||||
{
|
||||
field.SetValue(result, value);
|
||||
}
|
||||
}
|
||||
if (value != null)
|
||||
field.SetValue(result, value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Mapping failed for {field.Name}: {ex.Message}");
|
||||
Console.WriteLine($"Mapping failed for {field.Name}: {ex.InnerException?.Message ?? ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user