Roblox-File-Format/Utility/ImplicitMember.cs

102 lines
2.7 KiB
C#
Raw Permalink Normal View History

using System;
2020-07-06 00:04:20 +00:00
using System.Linq;
using System.Reflection;
namespace RobloxFiles.Utility
{
// This is a lazy helper class to disambiguate between FieldInfo and PropertyInfo
internal class ImplicitMember
{
2020-08-14 17:35:27 +00:00
private const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase;
2021-02-22 17:41:55 +00:00
2020-08-14 17:35:27 +00:00
private readonly object member;
2021-02-22 17:41:55 +00:00
private readonly string inputName;
2021-02-22 17:41:55 +00:00
private ImplicitMember(FieldInfo field, string name)
{
member = field;
inputName = name;
}
private ImplicitMember(PropertyInfo prop, string name)
{
member = prop;
inputName = name;
}
public static ImplicitMember Get(Type type, string name)
{
2020-07-06 00:04:20 +00:00
var field = type
.GetFields(flags)
.Where(f => f.Name == name)
.FirstOrDefault();
if (field != null)
2021-02-22 17:41:55 +00:00
return new ImplicitMember(field, name);
2020-07-06 00:04:20 +00:00
var prop = type
.GetProperties(flags)
.Where(p => p.Name == name)
.FirstOrDefault();
if (prop != null)
2021-02-22 17:41:55 +00:00
return new ImplicitMember(prop, name);
return null;
}
public Type MemberType
{
get
{
2021-02-22 17:41:55 +00:00
switch (member)
{
case PropertyInfo prop: return prop.PropertyType;
case FieldInfo field: return field.FieldType;
default: return null;
}
}
}
public object GetValue(object obj)
{
2021-02-22 17:41:55 +00:00
object result = null;
switch (member)
{
case FieldInfo field:
{
result = field.GetValue(obj);
break;
}
case PropertyInfo prop:
{
result = prop.GetValue(obj);
break;
}
}
return result;
}
public void SetValue(object obj, object value)
{
2021-02-22 17:41:55 +00:00
switch (member)
{
case FieldInfo field:
{
field.SetValue(obj, value);
return;
}
case PropertyInfo prop:
{
prop.SetValue(obj, value);
return;
}
}
RobloxFile.LogError($"Unknown field '{inputName}' in ImplicitMember.SetValue");
}
}
}