相关疑难解决方法(0)

我可以通过反射在没有装箱的情况下在结构上设置值吗?

实际上,我应该问:我怎么能这样做保持CLS合规?因为我能想到这样做的唯一方法如下,但使用其中任何一种方法__makeref,FieldInfo.SetValueDirect或者System.TypedReference通常只是使CLS合规性无效.

// code illustrating the issue:
TestFields fields = new TestFields { MaxValue = 1234 };  // test struct with one field

FieldInfo info = fields.GetType().GetField("MaxValue");  // get the FieldInfo

// actual magic, no boxing, not CLS compliant:
TypedReference reference = __makeref(fields);
info.SetValueDirect(reference, 4096);
Run Code Online (Sandbox Code Playgroud)

兼容的SetValueDirectSetValue,但它需要一个对象作为目标,因此我的结构将被装箱,使我在副本上设置一个值,而不是原始变量.

SetValue据我所知,通用对应物不存在.有没有其他方法通过反射设置(引用)结构的字段?

c# reflection struct boxing

10
推荐指数
2
解决办法
5539
查看次数

标签 统计

boxing ×1

c# ×1

reflection ×1

struct ×1