繁体   English   中英

结构异常上的 C# 反射 SetValue

[英]C# Reflection SetValue on a struct exception

我有一个结构体,它是我从工业控制器收集的一堆值。 我需要的是遍历结构体的所有字段以更新其值,但 SetValue 引发异常

对象与目标类型不匹配

public struct MyStruct
{
    public bool PLC_Manual_0_0 {get; set;}
    public bool PLC_Auto_0_1 {get; set; }
    public char PLC_KNR_9_14_0 {get; set;}
    public char PLC_KNR_10_15_0 {get; set;}
    public byte Reserva_16_0 {get; set;}
    public byte Reserva_17_0 {get; set;}
    public int Reserva_32_0 {get; set;}
    public int Reserva_34_0 {get; set;}
    public double Reserva_36_0 {get; set;}
    ...
}

public void ReadData()
{
    MyStruct mystruct = new MyStruct();
    Type mystruct_type = mystruct.GetType();
    PropertyInfo[] mystruct_properties = mystruct_type.GetProperties();
    foreach (PropertyInfo mystruct_property in mystruct_properties)
    {
        switch (mystruct_property.PropertyType.Name)
        {
            case "Boolean":
                bool bool_data = true;
                mystruct_property.SetValue(mystruct_property, bool_data);
                break;                             
            case "Byte":
                byte byte_data = 1;
                mystruct_property.SetValue(mystruct_property, byte_data);
                break;
            case "Char":
                char char_data = '1';
                mystruct_property.SetValue(mystruct_property, char_data);
                break;
            default:
                break;
        }
}

我还使用 mystruct_type 而不是 mystruct_property 尝试了 SetValue,结果相同。

我究竟做错了什么?

SetValue的第一个参数需要是您要设置其属性的实例,但您已经传递了属性信息。 但这无论如何都是没有希望的,因为MyStruct是一个值类型; SetValue只会对你传递给它的值的副本生效,而不是原始值。 如果您修复SetValue参数并将MyStruct更改为一个类,它将按预期工作。

暂无
暂无

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

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