forked from Blazor-Diagrams/Blazor.Diagrams
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReflectionUtils.cs
71 lines (61 loc) · 2.43 KB
/
ReflectionUtils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace SharedDemo
{
public static class ReflectionUtils
{
public static IEnumerable<PossibleOption> ExtractPossibleOptions<T>()
{
var type = typeof(T);
return ExtractPossibleOptions(type, string.Empty, Activator.CreateInstance(type));
}
private static IEnumerable<PossibleOption> ExtractPossibleOptions(Type type, string prefix, object instance)
{
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var name = $"{prefix}{property.Name}";
var propertyValue = instance == null ? null : property.GetValue(instance);
if (!IsPrimitiveOrNullable(property.PropertyType))
{
foreach (var entry in ExtractPossibleOptions(property.PropertyType, name + ".", propertyValue))
yield return entry;
continue;
}
var typeName = FormatPropertyType(property.PropertyType);
var @default = propertyValue?.ToString();
var description = property.GetCustomAttribute<DescriptionAttribute>().Description;
yield return new PossibleOption(name, typeName, @default, description);
}
}
private static string FormatPropertyType(Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
return $"{type.GetGenericArguments()[0].Name}?";
return type.Name;
}
private static bool IsPrimitiveOrNullable(Type type)
{
return type == typeof(object) ||
type == typeof(Type) ||
Type.GetTypeCode(type) != TypeCode.Object ||
Nullable.GetUnderlyingType(type) != null ||
typeof(Delegate).IsAssignableFrom(type);
}
}
public class PossibleOption
{
public string Name { get; }
public string Type { get; }
public string Default { get; }
public string Description { get; }
public PossibleOption(string name, string type, string @default, string description)
{
Name = name;
Type = type;
Default = @default;
Description = description;
}
}
}