我可以设置一个结构的值通过反射无拳? [英] Can I set a value on a struct through reflection without boxing?

查看:175
本文介绍了我可以设置一个结构的值通过反射无拳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其实,我应该问:我怎么能做到这一点的的仍然符合CLS?因为我能想到这样做是如下,但使用的唯一方法要么 __ makeref FieldInfo.SetValueDirect 或只是 System.TypedReference 一般CLS的失效符合。

Actually, I should've asked: how can I do this and remain CLS Compliant? Because the only way I can think of doing this is as follows, but using either __makeref, FieldInfo.SetValueDirect or just System.TypedReference in general invalidates CLS Compliance.

// 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 ,但它需要一个对象作为目标,因此,我的结构将被装箱,让我在副本而不是原始变量设置的值。

The compliant counterpart of SetValueDirect is SetValue, but it takes an object as the target, hence my struct will be boxed, making me setting a value on a copy, not the original variable.

的SetValue A一般对应不会因为据我所知存在。有没有通过反射设置的(参考一)结构该领域的任何其他方式?

A generic counterpart for SetValue doesn't exist as far as I know. Is there any other way of setting the field of a (reference to a) struct through reflection?

推荐答案

请符合CLS包装在SetValueDirect:

Make cls-compliant wrapper on SetValueDirect:

  var item = new MyStruct { X = 10 };

  item.GetType().GetField("X").SetValueForValueType(ref item, 4);


[CLSCompliant(true)]
static class Hlp
{
  public static void SetValueForValueType<T>(this FieldInfo field, ref T item, object value) where T : struct
  {
    field.SetValueDirect(__makeref(item), value);
  }
}

这篇关于我可以设置一个结构的值通过反射无拳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆