如何在使用Reflection.SetValue时提供转换?

我有一个假装成int的类,所以它已经超载了各种运算符;

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

但是,当我使用代码时

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

我得到了无效的演员。 我很困惑,两个调用似乎都试图在int上调用convert会失败,因为int不理解MyId类型(即使所有赋值运算符都在那里)。 对于这个解决方法的任何想法,我敢肯定我必须错过一些愚蠢的东西?

隐式转换是C#构造,无法通过reflection获得。 此外,通过reflection设置字段或属性意味着您必须预先提供适当的类型。 您可以尝试通过使用自定义TypeConverter(或其他一些自定义转换)来帮助在运行时转换类型,然后再使用reflection。 这是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);