如何在使用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
。
上述就是C#学习教程:如何在使用Reflection.SetValue时提供转换?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/989245.html