带有 GenecicType 错误的类型转换器

TypeConvertor with GenecicType Error

任何人都知道我如何修复这个错误:

Code generation for property '...' failed. Error was: 'Unable to cast object of type' '{The namespace}.EventType`1[System.Drawing.Color]' '{The namespace}.EventType`1[System.Object]'

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
    if (destinationType == typeof(InstanceDescriptor))
    {
        Type gT = value.GetType().GetGenericArguments()[0];
        Type cT = typeof(EventType<>).MakeGenericType(gT);

        ConstructorInfo cI = cT.GetConstructor(new Type[]
        {
            gT, gT, gT, gT, gT
        });

         // The error if from this line.
         // If i make EventType<Color> its works fine.
         // Any idea how i make this to work ?
        EventType<object> eT = (EventType<object>) value;

        return new InstanceDescriptor(cI, new object[]
        {
            eT.None, eT.Over, eT.Down, eT.Outside, eT.Invalid
        });
    }
    else if (destinationType == typeof(string))
    {
        return value.ToString();
    }
    throw new NotSupportedException($"The destination type: {destinationType}");
}

[TypeConverter(typeof(EventTypeConverter))]
public class EventType<T>
{
    public EventType(T none, T over, T down, T outside, T invalid)
    {
        None     = none;
        Over     = over;
        Down     = down;
        Outside  = outside;
        Invalid  = invalid;
    }

    public T None { get; set; }
    public T Over { get; set; }
    public T Down { get; set; }
    public T Outside { get; set; }
    public T Invalid { get; set; }
}

类 不支持方差,因此 EventType<T> 不能转换为 EventType<object>.

我看到的最简单的方法(在这种情况下通常会这样做)是在泛型方法中尽可能多地移动与泛型类型参数相关的代码,并通过反射或 DLR 动态调度调用它。

比如私有方法:

private static InstanceDescriptor ToInstanceDescriptor<T>(EventType<T> eT)
{
    var gT = typeof(T); 
    var cI = typeof(EventType<T>).GetConstructor(new Type[]
    {
        gT, gT, gT, gT, gT
    });
    return new InstanceDescriptor(cI, new object[]
    {
        eT.None, eT.Over, eT.Down, eT.Outside, eT.Invalid
    });
}

并动态调用它:

if (destinationType == typeof(InstanceDescriptor))
{
    return ToInstanceDescriptor((dynamic)value);
}