使用Linq表达式设置readoly / InitOnly成员字段(Set a readoly/InitOnly member field using Linq Expressions)

编程入门 行业动态 更新时间:2024-10-28 09:13:51
使用Linq表达式设置readoly / InitOnly成员字段(Set a readoly/InitOnly member field using Linq Expressions)

给定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.

更多推荐

本文发布于:2023-07-17 07:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1141321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   字段   成员   InitOnly   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!