How to provide conversion when using Reflection.SetValue?

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

public class MyId
{
    int value;
    public virtual int Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    public MyId(int value)
    {
        this.value = value;
    }


    public static implicit operator MyId(int rhs)
    {
        return new MyId(rhs);
    }

    public static implicit operator int(MyId rhs)
    {
        return rhs.Value;
    }


}

However, when I use code like

PropertyInfo.SetValue(myObj, 13, null)
OR
MyId myId = 13;
int x = Convert.ToInt32(myId);
IConvertible iConvertible = x as IConvertible;
iConvertible.ToType(typeof(MyId), CultureInfo.CurrentCulture);

I get an invalid listing. I am puzzled, both calls seem to be trying to call a conversion to int, which will not be executed, because int does not understand the type of MyId (although there are all assignment operators). Any ideas on a workaround for this, I'm sure I should be missing out on something stupid?

+3
source share
1 answer

# . , , . , TypeConverter ( ), . TypeConverter.

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);
    }               
}

, Custom.

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

, 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);
+2

All Articles