结构异常上的 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
更改为 class,它将按预期工作。
我有一个结构,它是我从工业控制器收集的一堆值。 我需要的是遍历结构的所有字段更新其值,但 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
更改为 class,它将按预期工作。