Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Reflection.SetValue时如何提供转换?_C#_Reflection - Fatal编程技术网

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

C# 使用Reflection.SetValue时如何提供转换?,c#,reflection,C#,Reflection,我有一个冒充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; } publi

我有一个冒充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实现的粗略示例

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

您是否尝试过实现
IConvertible
?到目前为止,您所描述的正是Int32所做的。。。提供一个围绕本机32位整数的对象框。我假设你的用例还有很多,但如果没有,就使用Int32。我已经在myid上完全实现了icovertable,但它看起来是在Int32上调用的,所以我不会影响它。如果你建议使用int而不是myid,那么不,就像你建议的那样,它做的远不止假装是int。只是补充一下,下面的工作很好,myid=13谢谢,这看起来有点开销,但这是一个很好的解决方案,再次感谢。