summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/ReflectionExtensions.cs
blob: 7a8b98b03c864c58fa964cbb5e01263c2662ea45 (plain)
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
72
73
74
75
76
´╗┐using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace Xamarin.Forms.Internals
{
	public static class ReflectionExtensions
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public static FieldInfo GetField(this Type type, Func<FieldInfo, bool> predicate)
		{
			return GetFields(type).FirstOrDefault(predicate);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static FieldInfo GetField(this Type type, string name)
		{
			return type.GetField(fi => fi.Name == name);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static IEnumerable<FieldInfo> GetFields(this Type type)
		{
			return GetParts(type, i => i.DeclaredFields);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static IEnumerable<PropertyInfo> GetProperties(this Type type)
		{
			return GetParts(type, ti => ti.DeclaredProperties);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static PropertyInfo GetProperty(this Type type, string name)
		{
			Type t = type;
			while (t != null)
			{
				TypeInfo ti = t.GetTypeInfo();
				PropertyInfo property = ti.GetDeclaredProperty(name);
				if (property != null)
					return property;

				t = ti.BaseType;
			}

			return null;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static bool IsAssignableFrom(this Type self, Type c)
		{
			return self.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo());
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static bool IsInstanceOfType(this Type self, object o)
		{
			return self.GetTypeInfo().IsAssignableFrom(o.GetType().GetTypeInfo());
		}

		static IEnumerable<T> GetParts<T>(Type type, Func<TypeInfo, IEnumerable<T>> selector)
		{
			Type t = type;
			while (t != null)
			{
				TypeInfo ti = t.GetTypeInfo();
				foreach (T f in selector(ti))
					yield return f;
				t = ti.BaseType;
			}
		}
	}
}