在反思的对象struct的接入领域 [英] Access fields of a Struct in an Object with Reflection
问题描述
我想使用反射(最终在编译时未知)对象
包括结构
。我得尽可能 TypedReference.MakeTypedReference
,但我已经碰了壁。
I'm trying to use reflection (ultimately on unknown at compile time) object
which include struct
. I've got as far as TypedReference.MakeTypedReference
but I've hit a wall.
下面是我和类结构
public class MyObject
{
public int Id;
public Money Amount;
}
public struct Money
{
public int Vaule;
public string Code;
}
这是我想设置代码,金额的在为MyObject使用反射。正如我上面提到的,我找不知道这些类型在编译时(这将是太容易了!)
And here is how I am trying to set "Code" of "Amount" in MyObject using reflection. As I mention above, I'm looking for a solution which does not know about these types at compile time (that would be too easy!)
下面的解决方案是我的代码到目前为止,(我用[0],[1],使代码更简单)
Here's the code I have so far (I've used [0], [1] to make the code simpler)
var obj = new MyObject() { Id = 1 };
obj.Amount.Vaule = 10;
obj.Amount.Code = "ABC";
FieldInfo[] objFields = obj.GetType().GetFields();
FieldInfo[] moneyFields = objFields[1].GetValue(obj).GetType().GetFields();
List<FieldInfo> fields = new List<FieldInfo>() { objFields[1] };
fields.AddRange( moneyFields );
TypedReference typeRef = TypedReference.MakeTypedReference(
objFields[1].GetValue( obj ), fields.ToArray() );
moneyFields[1].SetValueDirect( typeRef, "XXX" );
的
TypedReference.MakeTypedReference与炸毁; 字段信息不匹配目标类型。同样,如果我只是通过 objFields [1]
。而如果通过只是 moneyFields
我得到TypedReferences不能被重新定义为基元。
The TypedReference.MakeTypedReference blows up with; "FieldInfo does not match the target Type." Likewise if I just pass objFields[1]
. And if pass just moneyFields
I get "TypedReferences cannot be redefined as primitives."
为什么?比方说,我创建的随机测试夹具和要填充类字段随机数据:)
Why? Let's say I'm creating Random test fixtures and want to populate class fields with random data :)
推荐答案
坦率地说,有没有需要任何的 TypedReference
在这里 - 只是一个盒装的结构应很好地工作:
Frankly, there's no need whatsoever for TypedReference
here - just a boxed struct should work fine:
var amountField = obj.GetType().GetField("Amount");
object money = amountField.GetValue(obj);
var codeField = money.GetType().GetField("Code");
codeField.SetValue(money, "XXX");
amountField.SetValue(obj, money);
不过!我会告诉你的几件事情:
However! I will advise you of a few things:
- 公共领域,而不是性能通常不是个好主意;这往往会咬你以后
- 可变(可以创建之后不得更改,即结构)结构是的几乎没有的一个好主意,会咬人,甚至更多的时候,咬较硬
- 结合可变结构和公共领域的化合物,但使它很有问题在后来修改
- public fields instead of properties are not usually a good idea; that will often bite you later
- mutable structs (i.e. structs that can be changed after creation) are almost never a good idea, and will bite even more often, and bite harder
- combining mutable structs and public fields compounds it, but making it very problematic to change later
这篇关于在反思的对象struct的接入领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!