从现有 XDocument 创建新 XDocument
我有一个函数,它接受 XDocument 对象作为参数。
我需要循环访问不同集合中的许多其他对象,并为每个对象在 XDocument 上执行一些操作。但是 lopp 的每次迭代都需要传递给函数的原始 XDocument 的原始副本。
但是,如果我只是尝试对传递给函数的变量执行操作,它的行为就像一个指针 - 因此循环的每次迭代都会收到 XDocument ,无论它在最后一次迭代结束时留下什么状态,这在全部。
显然我需要制作 Xdocument 的副本,但我看不出有什么直接的方法可以做到这一点。尝试:
XDocument currentServerXml = XDocumentFromFunction.Document():
然后使用 currentServerXml 而不是 XDocumentFromFunction 为我提供具有相同指针和相同行为的相同副本。
如何为循环的每次迭代创建全新的数据副本?
I have a function which takes as an argument an XDocument object.
I need to loop through a number of other objects in a different collection and for each one of those objects, perform some actions on the XDocument. But each iteration of the lopp needs a pristine copy of the original XDocument that's passed to the function.
However if I just try and perform my operations on the variable that's passed into the function it behaves like a pointer - so each iteration of the loop receives the XDocument in whatever state it was left at the end of the last iteration which is no use at all.
Obviously I need to make a copy of the Xdocument but I can see no straightforward way of doing this. Trying:
XDocument currentServerXml = XDocumentFromFunction.Document():
And then using currentServerXml instead of XDocumentFromFunction gets me the same copy with the same pointer and the same behaviour.
How can I create a brand new copy of the data for each iteration of the loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在寻找采用 XDocument 的 XDocument 构造函数。这将创建传递的 XDocument 的深层副本。
示例代码:
You are looking for the XDocument constructor that takes an XDocument. This will create a deep copy of the passed XDocument.
Sample code:
将 XDocument 保存到流并从该流加载另一个实例。
编辑:您可以实现一个扩展方法“CreateCopy()”,它可以封装该解决方案,这样您就可以获得您所请求的易于使用的解决方案。
Save the XDocument to a stream and load another instance from that stream.
EDIT: You can implement an extension method "CreateCopy()" which may encapsulate that solution, so you can have your easy-to-use solution that you're requesting.
正如另一位受访者所建议的,直播将是最佳选择。然而,对于任何陷入我无法使用流的境地的人来说,最简单的方法是使用 TextReader:
瞧!
A stream would be the best option as the other respondant suggested. However for anyone stuck in my position of not being able to use a stream, the simplest method is to use a TextReader instead:
Voila!
MemberwiseClone
怎么样?How about
MemberwiseClone
?