DataContractSerializer 如何写入私有字段?
我了解 XMLSerializer 如何通过使用反射来确定应该使用哪些公共读/写字段或属性来序列化或反序列化 XML。然而 XMLSerializer 要求字段是公共的并且是读/写的。
但是,DataContractSerializer 能够读取或写入类中的完全私有字段。所以我想知道如果不明确给予 DataContractSerializer 对我的类的额外访问权限,这怎么可能。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
反射有很多特点。
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) whichType
the code is associated with. For example, if I create aDynamicMethod
passingtypeof(Foo)
as theowner
argument, then that dynamic method has full access to all members (including fields) onFoo
. For info,Delegate.CreateDelegate
provides similar access to otherwise protected data. SinceDataContractSerializer
doesn't worry about pre-generation, it can use this access.它的执行方式与
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 theDataContractSerializer
will.See this SO question and answers about reflection and changing of private fields.