【发布时间】:2012-03-29 14:36:38
【问题描述】:
实际上,我应该问:我怎样才能做到这一点并且保持 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);
SetValueDirect 的兼容对应物是SetValue,但它以对象为目标,因此我的结构将被装箱,使我在副本上设置一个值,而不是在原始变量上。
据我所知,SetValue 的通用对应项不存在。有没有其他方法可以通过反射设置(对a的引用)结构的字段?
【问题讨论】:
标签: c# reflection struct boxing