/// <summary> /// Sets a property on an object to a value. /// </summary> /// <param name="instance">The object whose property to set.</param> /// <param name="propertyName">The name of the property to set.</param> /// <param name="value">The value to set the property to.</param> public static void SetProperty(object instance, string propertyName, object value) { instance.ThrowIfNull(nameof(instance)); propertyName.ThrowIfNull(nameof(propertyName)); var instanceType = instance.GetType(); var pi = instanceType.GetProperty(propertyName); if (pi == null) { throw new ArgumentNullException($"No property '{propertyName}' found on the instance of type '{instanceType}'."); } if (!pi.CanWrite) { throw new ArgumentNullException($"The property '{propertyName}' on the instance of type '{instanceType}' does not have a setter."); } if (value?.GetType().IsAssignableFrom(pi.PropertyType) == false) { value = TypeConverterHelper.To(value, pi.PropertyType); } pi.SetValue(instance, value, Array.Empty <object>()); }
public static IEnumerable <string> GetConstants <TInput>() where TInput : class { return(typeof(TInput).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) .Where(fi => fi.IsLiteral && !fi.IsInitOnly) .Select(fi => TypeConverterHelper.To <string>(fi.GetRawConstantValue())) .ToList()); }