给定FieldInfo ,可以设置C# readonly / CLR InitOnly成员字段。
我何时以及为什么要这样做? 对于序列化程序,我创建了一个对象类型的空实例,然后我填充数据流中的所有字段。
对于实际问题:
有没有办法使用Linq Expressions实现这一点? 如果传递指向readonly / initonly字段的表达式, Expression.Assign导致异常。
或者我将不得不求助于IL发射(比FieldInfo更快)
Given a FieldInfo, it is possible to set a C# readonly / CLR InitOnly member field.
When and Why would I want to do this? its for a serializer, I create an empty instance of the object type, and I then populate all the fields from the data stream.
To the actual question:
Is there a way to achieve this using Linq Expressions also? the Expression.Assign results in a exception if you pass an expression pointing to the readonly/initonly field.
Or will I have to resort to IL emit to do this (faster than FieldInfo)
最满意答案
不, Expression.Assign检查字段的可分配性,即使你可以破解它来创建赋值表达式,它也不可验证且无法运行。 发送IL是最快的方法,它还允许分配指针(LINQ表达式不支持)。 你可以在这里看到如何发出类似的方法。
Nope, Expression.Assign checks the assignability of the field, and even if you could hack it to create the assignment expression, it wouldn't be verifiable and couldn't be run. Emitting IL is the fastest way to do it, and it would also allow assigning pointers (which aren't supported by LINQ Expressions). You can see here how to emit a similar method.
更多推荐
发布评论