[英]Extending System.Xml.Linq.XElement - internal CloneNode
I have class Foo
extending System.Xml.Linq.XElement
, but when I call 我有Foo
扩展System.Xml.Linq.XElement
类,但是当我打电话时
Foo parent = ..; Foo child = ..; parent.Add(child);
added child is not of type Foo
, it is of type XElement
. 添加的child不是Foo
类型,而是XElement
类型。
This is because of internal abstract XNode CloneNode()
which is called inside Add
method. 这是因为internal abstract XNode CloneNode()
在Add
方法内部被调用。
I can't override this because of internal. 由于内部原因,我无法覆盖它。 What are my options in this case? 在这种情况下,我有什么选择? I wouldn't like to override each function calling CloneNode()
. 我不想重写每个调用CloneNode()
函数。
For now I have one ugly solution, more like temporary hack than solution, not working generally, just to patch current code. 现在,我有一个丑陋的解决方案,更像是临时破解而不是解决方案,它不能正常工作,只是为了修补当前代码。 I am not sure that there is any nice solution, other than to rewrite code without extending XElement, so I will post this. 除了不扩展XElement即可重写代码外,我不确定是否有任何不错的解决方案,因此我将在此发布。
CloneNode is called in Add only when parent field is not null, but Parent property has only get, and parent field is internal. 仅当父字段不为null,但Parent属性只有get且父字段为内部时,才在Add中调用CloneNode。 So easiest way to fix my problem is to hide XElement Add with this in XElementExtended: 解决问题的最简单方法是在XElementExtended中将XElement Add隐藏起来:
static FieldInfo parentProperty = typeof(XElementExtended).GetField("parent",
BindingFlags.NonPublic | BindingFlags.Instance);
public void Add(XElementExtended element)
{
var el = new XElementExtended(element);
parentProperty.SetValue(el, null);
base.Add(el);
}
XElement as an entity is part of the XML model itself. XElement作为实体是XML模型本身的一部分。 You would extend it if you were adding some functionality to XML like a new kind of Node. 如果您要向XML添加某些功能(如新型Node),则可以对其进行扩展。 And even then, the XNode implementation is still correct because it knows absolutely nothing about your new XML. 即使这样,XNode实现仍然是正确的,因为它对您的新XML完全一无所知。 As far as I know XML isn't extensible it self, eg you can't add a new kind of node. 据我所知,XML本身是不可扩展的,例如,您不能添加新的节点。
If you're trying to Typify your XML data then the correct approach will be to build your data model separately and implement read/write methods on the root entities. 如果您要键入XML数据,那么正确的方法将是分别构建数据模型并在根实体上实现读/写方法。
If you want to tag your elements then you'll have to either build a wrapper around the whole model straight from XDocument or index the information on the side with Dictionary<XElement, something>
. 如果要标记元素,则必须直接从XDocument围绕整个模型构建包装器,或者使用Dictionary<XElement, something>
在侧面索引信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.