任何人都知道我如何修复此错误:
属性“ ...”的代码生成失败。错误是:“无法 类型''{ 名称空间} .EventType`1 [System.Drawing.Color]''{ 名称空间} .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; }
}
答案 0 :(得分:0)
类不支持方差,因此无法将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);
}