How to provide conversion when using Reflection.SetValue?

后端 未结 1 1156
萌比男神i
萌比男神i 2020-12-19 17:03

I have a class that pretends to be an int, so it has overloaded the various operators;

public class MyId
{
    int value;
    public virtual int Value
    {
         


        
1条回答
  •  青春惊慌失措
    2020-12-19 17:15

    Implicit conversions are a C# construct and are not available through reflection. Additionally, setting a field or property through reflection means that you must provide the appropriate type up front. You can attempt to circumvent this by using a custom TypeConverter (or some other means of custom conversion) to help convert your types at runtime prior to using reflection. Here's a rough example of a TypeConverter implementation.

    public class MyIdTypeConverter : TypeConverter
    {                
        public override object ConvertFrom(ITypeDescriptorContext context,
                                           System.Globalization.CultureInfo culture,
                                           object value)
        {   
            if (value is int)
                return new MyId((int)value);
            else if (value is MyId)
                return value;
            return base.ConvertFrom(context, culture, value);
        }               
    }
    

    Here's the type that we would be trying to set the Custom property on.

    public class Container
    {
        [TypeConverter(typeof(MyIdTypeConverter))]
        public MyId Custom { get; set; }                
    }
    

    The code to call it would have to check the attribute and perform the conversion ahead of time, after which it could call SetValue.

    var instance = new Container();
    var type = typeof(Container);
    var property = type.GetProperty("Custom");
    
    var descriptor = TypeDescriptor.GetProperties(instance)["Custom"];
    var converter = descriptor.Converter;                
    property.SetValue(instance, converter.ConvertFrom(15), null);
    

    0 讨论(0)
提交回复
热议问题