How to get or set a nested class property using C#
Summary: C# methods to set and get nested class property values.
If you need to get a set a value of a nested object property, here is a couple of functions that can help you do it using reflection (.NET 4.7, C#):
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | /// <summary> /// Gets the value of a nested object property. /// </summary> /// <param name="source"> /// Project that owns the property. /// < /param> /// <param name="name"> /// Name of the property. /// < /param> /// <returns> /// Property value (or <c>null</c>, if property does not exists). /// </returns> /// <remarks> /// <para> /// The code assumes that the property exists; /// if it does not, the code will return <c>null</c>. /// </para> /// <para> /// The property does not need to be nested. /// </para> /// <para> /// The code handles both class properties and fields. /// </para> /// </remarks> public static object GetPropertyValue ( object source, string name ) { if (name.Contains( "." )) { var names = name.Split( new char [] { '.' }, 2); return GetPropertyValue(GetPropertyValue(source, names[0]), names[1]); } else { PropertyInfo prop = null ; prop = source.GetType().GetProperty(name); if (prop != null ) return prop != null ? prop.GetValue(source) : null ; FieldInfo field = source.GetType().GetField(name); if (field == null ) return null ; return field.GetValue(source); } } /// <summary> /// Sets the value of a nested object property. /// </summary> /// <param name="target"> /// Object that owns the property to be set. /// < /param> /// <param name="name"> /// Name of the property. /// < /param> /// <param name="value"> /// Property value. /// < /param> /// <remarks> /// <para> /// The code assumes that the property exists; /// if it does not, the code will do nothing. /// </para> /// <para> /// The property does not need to be nested. /// </para> /// <para> /// The code handles both class properties and fields. /// </para> /// </remarks> public static void SetPropertyValue ( object target, string name, object value ) { var names = name.Split( '.' ); for ( int i = 0; i < names.Length - 1; i++) { PropertyInfo prop = target.GetType().GetProperty(names[i]); if (prop != null ) { target = prop.GetValue(target); continue ; } FieldInfo field = target.GetType().GetField(names[i]); if (field != null ) { target = field.GetValue(target); continue ; } return ; } PropertyInfo targetProp = target.GetType().GetProperty(names.Last()); if (targetProp != null ) targetProp.SetValue(target, value); } |
No comments:
Post a Comment