PKHeX/PKHeX.Core/Util/ReflectUtil.cs

78 lines
3.1 KiB
C#
Raw Normal View History

2016-07-16 17:00:50 +00:00
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
2016-07-16 17:00:50 +00:00
using System.Reflection;
namespace PKHeX.Core
2016-07-16 17:00:50 +00:00
{
public static class ReflectUtil
2016-07-16 17:00:50 +00:00
{
public static bool IsValueEqual(object obj, string propertyName, object value)
2016-07-16 17:00:50 +00:00
{
PropertyInfo pi = obj.GetType().GetTypeInfo().GetDeclaredProperty(propertyName);
if (pi == null)
return false;
2016-07-16 17:00:50 +00:00
var v = pi.GetValue(obj, null);
var c = ConvertValue(value, pi.PropertyType);
2016-07-16 17:00:50 +00:00
return v.Equals(c);
}
public static void SetValue(object obj, string propertyName, object value)
2016-07-16 17:00:50 +00:00
{
PropertyInfo pi = obj.GetType().GetTypeInfo().GetDeclaredProperty(propertyName);
pi.SetValue(obj, ConvertValue(value, pi.PropertyType), null);
2016-07-16 17:00:50 +00:00
}
public static object GetValue(object obj, string propertyName)
{
PropertyInfo pi = obj.GetType().GetTypeInfo().GetDeclaredProperty(propertyName);
return pi.GetValue(obj, null);
}
public static object GetValue(Type t, string propertyName) => t.GetTypeInfo().GetDeclaredProperty(propertyName).GetValue(null);
public static void SetValue(Type t, string propertyName, object value) => t.GetTypeInfo().GetDeclaredProperty(propertyName).SetValue(null, value);
public static IEnumerable<string> GetPropertiesStartWithPrefix(Type type, string prefix)
{
return type.GetTypeInfo().DeclaredProperties
.Where(p => p.Name.StartsWith(prefix, StringComparison.Ordinal))
.Select(p => p.Name);
}
public static IEnumerable<string> GetPropertiesCanWritePublic(Type type)
{
return type.GetTypeInfo().DeclaredProperties
.Where(p => p.CanWrite && p.SetMethod.IsPublic)
.Select(p => p.Name);
}
public static IEnumerable<string> GetPropertiesCanWritePublicDeclared(Type type)
{
return GetPropertiesCanWritePublic(type);
}
public static bool HasProperty(this Type type, string name)
{
return type.GetTypeInfo().GetDeclaredProperty(name) != null;
2016-09-30 22:12:23 +00:00
}
public static bool HasPropertyAll(this Type type, Type Base, string name)
2016-09-30 22:12:23 +00:00
{
return HasProperty(type, name) || HasProperty(Base, name);
}
private static object ConvertValue(object value, Type type)
{
if (type == typeof(DateTime?)) // Used for PKM.MetDate and other similar properties
{
return DateTime.TryParseExact(value.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateValue)
? new DateTime?(dateValue)
: null;
}
// Convert.ChangeType is suitable for most things
return Convert.ChangeType(value, type);
}
public static bool? GetBooleanState(object obj, string prop)
{
return obj.GetType().HasProperty(prop) ? GetValue(obj, prop) as bool? : null;
}
2016-07-16 17:00:50 +00:00
}
}