jeudi 27 août 2020

C# Reflection SetValue on a struct exception

I have a struct that is a bunch of values that I collect from an industrial controller. What I need is to go through all the struct's fields updating its values, but SetValue throws an exception

"Object does not match target type"

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

I also tried SetValue using mystruct_type instead of mystruct_property with the same result.

What am I doing wrong?





Aucun commentaire:

Enregistrer un commentaire