我想写个方法来通过结构体字段的 名称和值来批量设置参数,但是现在结构体作为参数传递后,方法中结构体参数改变了,但是方法外部的没变。
怎么解决这个问题
public static void SetStructValue(ref object pStruct, string name, object value)
{
Type type = pStruct.GetType();
FieldInfo fieldInfo = type.GetField(name);
if (fieldInfo != null)
{
object v = Convert.ChangeType(value, fieldInfo.FieldType);
fieldInfo.SetValue(pStruct, v);
}
}
public struct TTrapPrm
{
public double acc;
public double dec;
public double velStart;
public short smoothTime;
}
找到办法了,先把结构体转换为object,运行完成后再将object 赋值给 struct
连 ref 都能去掉
TTrapPrm trapPara = new TTrapPrm();
object obj = trapPara;
SetStructValue(obj, "acc", 10);
trapPara = (TTrapPrm)obj;
不知道有没有更好的办法
试过了,另一种实现方法
public static void SetStructValue1<T>(ref T scr, string name, object value)
{
object pStruct = scr as object;
Type type = pStruct.GetType();
FieldInfo fieldInfo = type.GetField(name);
if (fieldInfo != null)
{
object v = Convert.ChangeType(value, fieldInfo.FieldType);
fieldInfo.SetValue(pStruct, v);
}
scr = (T)pStruct;
}
结构体是值类型,参数是object,传递的时候装箱。方法体内修改的是装箱后的object,修改这个object,调用处的值类型结构体不会变。你把ref object改成ref TTrapPrm。但是直接通过反射写应该还是错的,在方法体内可以先装箱,反射赋值之后拆箱。随手写了一下,应该有更好的方法仅供参考
结构属于值类型,不能将它作为引用类型看待
https://www.cnblogs.com/lusunqing/p/3749275.html
要实现修改,用这个方法:
public static void SetStructValue(ref TTrapPrm pStruct, string name, object value)
{
Type type = pStruct.GetType();
FieldInfo fieldInfo = type.GetField(name);
TypedReference reference = __makeref(pStruct);
if (fieldInfo != null)
{
fieldInfo.SetValueDirect(reference, value);
}
}
内容重复,,,,,
unsafe {
public static void SetStructValue(TTrapPrm * pStruct, string name, object value)
{
Type type = pStruct.GetType();
FieldInfo fieldInfo = type.GetField(name);
if (fieldInfo != null)
{
object v = Convert.ChangeType(value, fieldInfo.FieldType);
fieldInfo.SetValue(*pStruct, v);
}
}
}
不行的话 找个 Object类型去传参数。。