DataContractSerializer 如何写入私有字段?

发布于 2024-08-27 23:45:38 字数 206 浏览 2 评论 0原文

我了解 XMLSerializer 如何通过使用反射来确定应该使用哪些公共读/写字段或属性来序列化或反序列化 XML。然而 XMLSerializer 要求字段是公共的并且是读/写的。

但是,DataContractSerializer 能够读取或写入类中的完全私有字段。所以我想知道如果不明确给予 DataContractSerializer 对我的类的额外访问权限,这怎么可能。

I understand how XMLSerializer could work by using reflection to figure out what public read/write fields or properties it should be using to serialize or de-serialize XML. Yet XMLSerializer requires that the fields be public and read/write.

However, DataContractSerializer is able to read or write to or from completely private fields in a class. So I'm wondering how this is even possible with out explicitly giving DataContractSerializer additional access rights to my class(es).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟沫凡尘 2024-09-03 23:45:38

反射有很多特点。 XmlSerializer 通过“sgen.exe”能够将序列化代码预先构建为二进制文件 (dll)。这在某些不允许动态代码的场景中很有用,但 dll(就像您的代码一样)仅限于可访问的 API。

然而......反射并没有这个限制,并且只要有足够的访问权限,您几乎可以做任何事情。为了提高性能,您可能不希望直接大量使用反射,但如果您有足够的权限直接在内存中创建 IL (DynamicMethod),那么您可以告诉它(基于每个动态方法)与代码关联的Type。例如,如果我创建一个将 typeof(Foo) 作为 owner 参数传递的 DynamicMethod,则该动态方法可以完全访问所有成员 (包括字段)在 Foo 上。有关信息,Delegate.CreateDelegate 提供对其他受保护数据的类似访问。由于 DataContractSerializer 不担心预生成,因此它可以使用此访问权限。

Reflection has many features. XmlSerializer has, via "sgen.exe" the ability to pre-build the serialization code to a binary (dll). This is useful in some scenarios that don't allow dynamic code, but dlls (just like your code) are limited to the accessible API.

However... reflection isn't this limited, and with enough access you can do pretty much anything. For performance you probably don't want to be using reflection directly a lot, but if you have enough permissions to create IL directly in memory (DynamicMethod), then you can tell it (on a per-dynamic-method basis) which Type the code is associated with. For example, if I create a DynamicMethod passing typeof(Foo) as the owner argument, then that dynamic method has full access to all members (including fields) on Foo. For info, Delegate.CreateDelegate provides similar access to otherwise protected data. Since DataContractSerializer doesn't worry about pre-generation, it can use this access.

筑梦 2024-09-03 23:45:38

它的执行方式与 XMLSerializer 相同,即使用反射。

不同之处在于 XMLSerializer 不会触及私有字段,但 DataContractSerializer 会。

请参阅这个所以问题和答案关于私人领域的反思和改变。

It does it the same way the XMLSerializer does, by using reflection.

The difference is that XMLSerializer will not touch private fields but the DataContractSerializer will.

See this SO question and answers about reflection and changing of private fields.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文