From 6627c016f232341340ae9e0803f5358f47cf1f9c Mon Sep 17 00:00:00 2001 From: David Hall Date: Wed, 8 May 2019 12:50:26 -0600 Subject: [PATCH] Added Get/SetFieldValue extension methods --- Core/Extensions/ReflectionExtensions.cs | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Core/Extensions/ReflectionExtensions.cs b/Core/Extensions/ReflectionExtensions.cs index ac7d556d..346f76a4 100644 --- a/Core/Extensions/ReflectionExtensions.cs +++ b/Core/Extensions/ReflectionExtensions.cs @@ -61,6 +61,29 @@ namespace Vanara.Extensions bool ImplIEnumT(Type t) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>); } + /// Gets a named field value from an object. + /// The expected type of the field to be returned. + /// The object from which to retrieve the field. + /// Name of the field. + /// The field value. + public static T GetFieldValue(this object obj, string fieldName) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + return (T)obj.GetType().InvokeMember(fieldName, BindingFlags.GetField | bindingFlags, null, obj, null, null); + } + + /// Gets a named field value from an object. + /// The expected type of the field to be returned. + /// The object from which to retrieve the field. + /// Name of the field. + /// The default value to return in the instance that the field is not found. + /// The field value, if found, or the if not. + public static T GetFieldValue(this object obj, string fieldName, T defaultValue) + { + try { return GetFieldValue(obj, fieldName); } + catch { return defaultValue; } + } + /// Gets a named property value from an object. /// The expected type of the property to be returned. /// The object from which to retrieve the property. @@ -240,6 +263,17 @@ namespace Vanara.Extensions return ret; } + /// Sets a named field on an object. + /// The type of the field to be set. + /// The object on which to set the field. + /// Name of the field. + /// The field value to set on the object. + public static void SetFieldValue(this object obj, string fieldName, T value) + { + try { obj?.GetType().InvokeMember(fieldName, BindingFlags.SetField | bindingFlags, null, obj, new object[] { value }, null); } + catch { } + } + /// Sets a named property on an object. /// The type of the property to be set. /// The object on which to set the property.