Tri-Inspector/Editor/Resolvers/InstanceMethodValueResolver.cs

70 lines
2.1 KiB
C#
Raw Normal View History

2022-05-09 08:06:51 -04:00
using System;
using System.Reflection;
2022-05-11 12:48:50 -04:00
using UnityEngine;
2022-05-09 08:06:51 -04:00
namespace TriInspector.Resolvers
{
2022-05-11 12:48:50 -04:00
internal sealed class InstanceMethodValueResolver<T> : ValueResolver<T>
2022-05-09 08:06:51 -04:00
{
private readonly MethodInfo _methodInfo;
2022-05-11 12:48:50 -04:00
public static bool TryResolve(TriPropertyDefinition propertyDefinition, string expression,
out ValueResolver<T> resolver)
2022-05-09 08:06:51 -04:00
{
2022-08-17 13:46:26 -04:00
var parentType = propertyDefinition.OwnerType;
2022-05-09 08:06:51 -04:00
if (parentType == null)
{
resolver = null;
return false;
}
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
foreach (var methodInfo in parentType.GetMethods(flags))
{
2022-05-11 12:48:50 -04:00
if (methodInfo.Name == expression &&
typeof(T).IsAssignableFrom(methodInfo.ReturnType) &&
2022-05-09 08:06:51 -04:00
methodInfo.GetParameters() is var parameterInfos &&
parameterInfos.Length == 0)
{
2022-05-11 12:48:50 -04:00
resolver = new InstanceMethodValueResolver<T>(methodInfo);
2022-05-09 08:06:51 -04:00
return true;
}
}
resolver = null;
return false;
}
2022-05-11 12:48:50 -04:00
private InstanceMethodValueResolver(MethodInfo methodInfo)
2022-05-09 08:06:51 -04:00
{
_methodInfo = methodInfo;
}
public override bool TryGetErrorString(out string error)
{
error = "";
return false;
}
2022-05-11 12:48:50 -04:00
public override T GetValue(TriProperty property, T defaultValue = default)
2022-05-09 08:06:51 -04:00
{
var parentValue = property.Owner.GetValue(0);
2022-05-09 08:06:51 -04:00
2022-05-11 12:48:50 -04:00
try
{
return (T) _methodInfo.Invoke(parentValue, Array.Empty<object>());
}
catch (Exception e)
{
if (e is TargetInvocationException targetInvocationException)
{
e = targetInvocationException.InnerException;
}
Debug.LogException(e);
return defaultValue;
}
2022-05-09 08:06:51 -04:00
}
}
}