ファイル

52 行
1.4 KiB
C#

using System.Reflection;
namespace UndoTree;
internal static class UndoTreeMembers
{
const BindingFlags Instance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
public static PropertyInfo? PropertyOf(object target, string name)
{
try
{
return target.GetType().GetProperty(name, Instance);
}
catch (AmbiguousMatchException)
{
return null;
}
}
public static object? ValueOf(object target, PropertyInfo property)
{
try
{
return property.GetValue(target);
}
catch (Exception exception) when (exception is TargetInvocationException or ArgumentException)
{
return null;
}
}
public static List<object>? ItemsOf(object? items)
{
if (items is not System.Collections.IEnumerable sequence)
return null;
var list = sequence.Cast<object?>().ToList();
return list.Contains(null) ? null : list.OfType<object>().ToList();
}
public static Type? ElementOf(Type type)
{
var elements = type.GetInterfaces().Append(type)
.Where(candidate => candidate.IsGenericType && candidate.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.Select(candidate => candidate.GetGenericArguments()[0])
.Distinct()
.ToArray();
return elements.Length == 1 ? elements[0] : null;
}
}