AR Design
UBC EML collab with UBC SALA - visualizing IoT data in AR
ShowIfAttribute.cs
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License. See LICENSE in the project root for license information.
3 
4 using System;
5 using System.Reflection;
6 #if UNITY_EDITOR
7 using UnityEditor;
8 #endif
9 
10 namespace HoloToolkit.Unity
11 {
12  // Base class for show / hide - shows or hides fields & properties in the editor based on the value of a member in the target object
13  public abstract class ShowIfAttribute : Attribute
14  {
15  public string MemberName { get; protected set; }
16  public bool ShowIfConditionMet { get; protected set; }
17 
18 #if UNITY_EDITOR
19  public abstract bool ShouldShow(object target);
20 
21  protected static object GetMemberValue(object target, string memberName)
22  {
23  if (target == null)
24  throw new NullReferenceException("Target cannot be null.");
25 
26  if (string.IsNullOrEmpty(memberName))
27  throw new NullReferenceException("MemberName cannot be null.");
28 
29  Type targetType = target.GetType();
30 
31  MemberInfo[] members = targetType.GetMember(memberName);
32  if (members.Length == 0)
33  throw new MissingMemberException("Couldn't find member '" + memberName + "'");
34 
35  object memberValue;
36 
37  switch (members[0].MemberType)
38  {
39  case MemberTypes.Field:
40  FieldInfo fieldInfo = targetType.GetField(memberName);
41  memberValue = fieldInfo.GetValue(target);
42  break;
43 
44  case MemberTypes.Property:
45  PropertyInfo propertyInfo = targetType.GetProperty(memberName);
46  memberValue = propertyInfo.GetValue(target, null);
47  break;
48 
49  default:
50  throw new MissingMemberException("Member '" + memberName + "' must be a field or property");
51  }
52  return memberValue;
53  }
54 
55  protected static bool IsNullable(object target, string memberName)
56  {
57  if (target == null)
58  throw new NullReferenceException("Target cannot be null.");
59 
60  if (string.IsNullOrEmpty(memberName))
61  throw new NullReferenceException("MemberName cannot be null.");
62 
63  Type targetType = target.GetType();
64 
65  MemberInfo[] members = targetType.GetMember(memberName);
66  if (members.Length == 0)
67  throw new MissingMemberException("Couldn't find member '" + memberName + "'");
68 
69  Type memberType = members[0].DeclaringType;
70 
71  if (!memberType.IsValueType)
72  return true;
73 
74  if (Nullable.GetUnderlyingType(memberType) != null)
75  return true;
76 
77  return false;
78  }
79 #endif
80  }
81 }