繁体   English   中英

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

[英]How to provide conversion when using 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#构造,无法通过反射获得。 此外,通过反射设置字段或属性意味着您必须预先提供适当的类型。 您可以尝试通过使用自定义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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM