how to set nullable type via reflection code ( c#)?

后端 未结 8 1356
我寻月下人不归
我寻月下人不归 2020-12-28 16:05

I need to set the properties of a class using reflection.

I have a Dictionary with property names and string values.

Inside

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 16:33

    I have used the following solution, avoiding use of type converter for taking more control over code.

    I wrote a helper class for supporting operations

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Reflection;
    using System.Text;
    
    public static class ObjectExtensions
    {
        /// 
        /// Enable using reflection for setting property value 
        /// on every object giving property name and value.
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static bool SetProperty(this T target, string propertyName, object value)
        {
            PropertyInfo pi = target.GetType().GetProperty(propertyName);
            if (pi == null)
            {
                Debug.Assert(false);
                return false;
            }
    
            try
            {
                // Convert the value to set to the properly type
                value = ConvertValue(pi.PropertyType, value);
    
                // Set the value with the correct type
                pi.SetValue(target, value, null);
            }
            catch (Exception ex)
            {
                Debug.Assert(false);
                return false;
            }
            return true;
        }
    
    
        private static object ConvertValue(Type propertyType, object value)
        {
            // Check each type You need to handle
            // In this way You have control on conversion operation, before assigning value
            if (propertyType == typeof(int) ||
                propertyType == typeof(int?))
            {
                int intValue;
                if (int.TryParse(value.ToString(), out intValue))
                    value = intValue;
            }
            else if (propertyType == typeof(byte) ||
                    propertyType == typeof(byte?))
            {
                byte byteValue;
                if (byte.TryParse(value.ToString(), out byteValue))
                    value = byteValue;
            }
            else if (propertyType == typeof(string))
            {
                value = value.ToString();
            }
            else
            {
                // Extend Your own handled types
                Debug.Assert(false);
            }
    
            return value;
        }
    }
    

    Note: When You set a nullable value (eg. int?, the value need to be almost an integer or castable type. You cannot set int on a byte?. So, You need to convert properly. See ConvertValue() code, that checks either for type (int) and corresponding nullable type (int?) )

    This is code for setting values with the required data structure, Dictionary.

        public class Entity
        {
            public string Name { get; set; }
            public byte? Value { get; set; }
        }
    
        static void SetNullableWithReflection()
        {
            // Build array as requested
            Dictionary props = new Dictionary();
            props.Add("Name", "First name");
            props.Add("Value", "1");
    
            // The entity
            Entity entity = new Entity();
    
            // For each property to assign with a value
            foreach (var item in props)
                entity.SetProperty(item.Key, item.Value);
    
            // Check result
            Debug.Assert(entity.Name == "First name");
            Debug.Assert(entity.Value == 1);
        }
    

提交回复
热议问题