问题描述
在构建文档时,我想对XElement进行子类化,以添加一些更强大的类型检查.不幸的是,我发现自己被限制在库的重要部分之外.
I would like to subclass XElement to add a bit of stronger type checking when I am constructing a document. Unfortunately I found to be locked out of the important part of the library.
// only illustrative
class TopLevelBlock:XElement {
class TopLevelBlock : XElement {
TopLevelBlock(XName name):base(name){}}class Parargaph:TopLevelBLock {
TopLevelBlock(XName name) : base(name) {}}class Parargaph : TopLevelBLock {
Paragraph():base(W.p){}
Paragraph() : base(W.p) {}
//由于内部限制,无法实现
// not possible due to internal restriction
//公共重写XNode CloneNode(){
// 返回新的段落(this);
//}}类表:TopLevelBlock {}class StructuredDocumentTag:TopLevelBlock {}
// public override XNode CloneNode() {
// return new Paragraph(this);
// }}class Table : TopLevelBlock {}class StructuredDocumentTag : TopLevelBlock {}
para = Paragraph();
para = Paragraph();
parent.Add(para); //将保留为段落
parent.Add(para); // it will stay as Paragraph
parent.Add(para); //由于CloneNode类型的结果将更改为XElement
parent.Add(para); // as a result of CloneNode type will change to XElement
一切都很好,只要我正在构建文档并且不调用任何触发CloneNode的LINQ转换即可.当我点击CloneNode时,所有内容都将降级为XElement.
Everything is fine as long as I am constructing document and not calling any LINQ transformations triggering CloneNode. As soon as I hit CloneNode, everything gets downgraded to XElement.
CloneNode已被标记为虚拟,但不幸的是内部.将来是否有机会放宽此限制?
The CloneNode is marked already as virtual, but unfortunately internal. Is there any chance to relax this restriction in the future?
也许使用c#/.net的其他机制可以更好地完成我想做的事情.欢迎任何建议.
Perhaps there is a better way of accomplishing what I am trying to do using other mechanism of c#/.net. Any suggestions are welcome.
-pawel
在将XText子类化时,其他人报告了类似的困难,http://blogs.msdn.com/b/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
Other people reported similar difficulties when subclassing XText, http://blogs.msdn.com/b/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
推荐答案
class TopLevelBlock
{
readonly XElement doc;
TopLevelBlock(string name)
{
doc = new XElement((XName)name);
doc.SetAttributeValue("someAttribute","");
}
public int someAttribute
{
get
{
return int.Parse(doc.Attribute("someAttribute").Value);
}
set
{
doc.SetAttributeValue("someAttribute", value.ToString());
}
}
}
也许是XML序列化.
David
这篇关于LINQ to XML-子类化XElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!