예제 #1
0
        /// <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)
        {
            if (instance == null)
            {
                throw new GeneralException(nameof(instance));
            }
            if (propertyName == null)
            {
                throw new GeneralException(nameof(propertyName));
            }

            var instanceType = instance.GetType();
            var pi           = instanceType.GetProperty(propertyName);

            if (pi == null)
            {
                throw new GeneralException("No property '{0}' found on the instance of type '{1}'.", propertyName, instanceType);
            }
            if (!pi.CanWrite)
            {
                throw new GeneralException("The property '{0}' on the instance of type '{1}' does not have a setter.", propertyName, instanceType);
            }
            if (value != null && !value.GetType().IsAssignableFrom(pi.PropertyType))
            {
                value = TypeConverterHelper.To(value, pi.PropertyType);
            }
            pi.SetValue(instance, value, Array.Empty <object>());
        }
예제 #2
0
 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());
 }