简体   繁体   English

从FieldInfo获取对变量的引用

[英]Get reference to variable from FieldInfo

I am working on a project where a field name from XML is loaded and the field with that name is returned and added to the current object. 我正在开发一个项目,其中加载了XML的字段名称,并返回具有该名称的字段并将其添加到当前对象。 The problem is that FieldInfo.GetValue seems to return the current value of the field, not a reference. 问题是FieldInfo.GetValue似乎返回字段的当前值,而不是引用。 Is there any way to get around this? 有没有办法解决这个问题?

No unfortunately there is not. 不幸的是没有。 The design of FieldInfo.GetValue is to provide the value and not a reference. FieldInfo.GetValue的设计是提供值而不是引用。 There is no other suitable method on FieldInfo to provide a reference either. FieldInfo上没有其他合适的方法来提供引用。

One reason why is that doing so would be simply unsafe. 其中一个原因是,这样做根本就不安全。 Imagen the scenario where the object is a struct on the stack. Imagen对象是堆栈上的struct的场景。 If a FieldInfo could provide a reference to a field of that struct then it would be supplying a reference to a piece of the stack which could go away at any moment. 如果FieldInfo可以提供对该struct的字段的引用,那么它将提供对栈的一部分的引用,该引用可能随时消失。 Reading or writing that reference after the stack went away would be incorrect and a type safety violation. 在堆栈消失后读取或写入该引用将是不正确的并且类型安全违规。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM