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

后端 未结 8 1344
我寻月下人不归
我寻月下人不归 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:21

    I've created small sample. If you have any questions regarding this code, please add comments.

    EDIT: updated sample based on great comment by Marc Gravell

    class Program
    {
        public int? NullableProperty { get; set; }
    
        static void Main(string[] args)
        {
            var value = "123";
            var program = new Program();
            var property = typeof(Program).GetProperty("NullableProperty");
    
            var propertyDescriptors = TypeDescriptor.GetProperties(typeof(Program));
            var propertyDescriptor = propertyDescriptors.Find("NullableProperty", false);
            var underlyingType =  
                Nullable.GetUnderlyingType(propertyDescriptor.PropertyType);
    
            if (underlyingType != null)
            {
                var converter = propertyDescriptor.Converter;
                if (converter != null && converter.CanConvertFrom(typeof(string)))
                {
                    var convertedValue = converter.ConvertFrom(value);
                    property.SetValue(program, convertedValue, null);
                    Console.WriteLine(program.NullableProperty);
                }
            }
    
        }
    }
    

提交回复
热议问题