C#在运行时为Array.SetValue类型转换

Iai*_*oat 5 c# arrays reflection casting runtime

我正在尝试使用反射创建一个数组,并将值插入其中.我正在尝试为许多不同类型执行此操作,因此需要一个createAndFillArray能够执行此操作的函数:

String propertyName1 = "prop1";
String propertyName2 = "prop2";

Type t1 = typeof(myType).getProperty(propertyName1).PropertyType.getElementType();
Type t2 = typeof(myType).getProperty(propertyName2).PropertyType.getElementType();

double exampleA = 22.5;
int exampleB = 43;

Array arrA = createAndFillArray(t1, exampleA);
Array arrB = createAndFillArray(t2, exampleB);

private Array createAndFillArray(Type t, object val){
    Array arr = Array.CreateInstance( t, 1); //length 1 in this example only, real-world is of variable length.
    arr.SetValue( val, 0 ); //this causes the following error: "System.InvalidCastException : Object cannot be stored in an array of this type."
    return arr;
}
Run Code Online (Sandbox Code Playgroud)

A级如下:

public class A{
    public A(){}

    private double val;
    public double Value{
        get{ return val; }
        set{ this.val = value; }
    }

    public static implicit operator A(double d){
        A a = new A();
        a.Value = d;
        return a;
    }
}
Run Code Online (Sandbox Code Playgroud)

和B类非常相似,但有int:

public class B{
    public B(){}

    private double val;
    public double Value{
        get{ return val; }
        set{ this.val = value; }
    }

    public static implicit operator B(double d){
        B b = new B();
        b.Value = d;
        return b;
    }
}
Run Code Online (Sandbox Code Playgroud)

和myType类似如下:

public class myType{
    public A prop1{ get; set; }
    public B prop2{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我希望隐式运算符可以确保将double转换为A类,或者将int转换为B类,并避免错误; 但这显然不是这样.

以上内容用于自定义反序列化类,该类从自定义数据格式获取数据并填充相应的.Net对象属性.我是通过反射和运行时这样做的,所以我认为两者都是不可避免的.我的目标是C#2.0框架.

我有几十个,甚至几百个类似于A和的类B,所以我更愿意找到一个改进createAndFillArray方法的解决方案而不是改变这些类的解决方案.

shf*_*301 3

下面是一个使用反射来查找转换方法的示例。因此,如果您可以在您的类型上获取该方法并自行进行转换。

复制自:http ://bytes.com/topic/c-sharp/answers/903775-getting-operators-using-reflection

//EndType is the type I want to PRODUCE
//StartType is the type I am pulling data FROM
MethodInfo mi = EndType.GetMethod(
    "op_Implicit", 
    (BindingFlags.Public | BindingFlags.Static), 
    null, 
    new Type[] { StartType }, 
    new ParameterModifier[0]
);
//Now if mi is NOT null, it means there is an operator that allows for converting StartType to EndType, if it is null, there isn't one
Run Code Online (Sandbox Code Playgroud)