2016-12-07 76 views
2

XAttributeXElement都源自XObject类型。是否可以为XAttribute和XElement编写一个方法?

两者都有Value属性。

到目前为止,这是我想出做我想做什么:

string FooMyXObject(XObject bar){ 
    if (bar.NodeType == NodeType.Element) 
     return (bar as XElement).Value; 
    else if (bar.NodeType == NodeType.XAttribute) 
     return (bar as XAttribute).Value; 
    else 
     throw new Exception("Generic Fail Message"); 
} 

这种感觉沉闷。我希望有一些方法可以使这个不那么笨拙。从XObject访问Value属性的某种方式,因为它们都具有字符串属性名称Value

这是可能的,还是我只是被迫以如此笨拙的方式去做?

+1

['XText'](https://msdn.microsoft.com/en-us/library/system.xml.linq.xtext(v = vs.110).aspx)和['XComment'](https ://msdn.microsoft.com/en-us/library/system.xml.linq.xcomment(v = vs.110).aspx)也有一个没有公共基类的Value属性。真的有点烦人。这正是“IHasValue”接口适合的情况。 – dbc

回答

2

你可以施放bardynamic避免单独的分支:

string FooMyXObject(XObject bar){ 
    if (bar.NodeType == NodeType.Element || bar.NodeType == NodeType.XAttribute) 
     return ((dynamic)bar).Value; 
    else 
     throw new Exception("Generic Fail Message"); 
} 
+0

我喜欢这个。它肯定比我正在做的更好(和GetType().GetProperty(“Value”).GetValue(Bar).ToString()'方法)。 – Will

+0

像这样使用'dynamic'时会出现性能问题。 OP在他的问题中提供的代码在性能方面表现会更好,我建议使用它。 – MarcinJuraszek

2

如果在XObject上定义了.Value属性,那么你可以用泛型来写这个。

string FooMyXObject<T>(T bar) where T : XObject 
{ 
    return bar.Value; 
} 

如果不是的话,那么你应该考虑将其移动到基类,如果它是派生类的常用功能。

编辑: 如果Value属性不在基类中,那么您的代码几乎是正确的。也许你可以重构它像这样使用的情况下更容易扩展:

string FooMyXObject(XObject bar) 
{ 
    switch(bar.NodeType) 
    { 
     case NodeType.Element: 
      return (bar as XElement).Value; 
     case NodeType.XAttribute: 
      return (bar as XAttribute).Value; 
     default: 
      throw new Exception("Generic Fail Message"); 
    } 
} 

或只是为了好玩

string FooMyXObject(XObject bar) 
    { 
     try 
     { 
      dynamic temp = bar; 
      return temp.Value; 
     } 
     catch() 
     { 
      throw new Exception("Generic Fail Message"); 
     } 
    } 
+1

'Value'不是在'XObject'类型中定义的属性。 – Will

0

@meganaut和@dasblinkenlight给出的答案都是正确的,但还有更多要说的。

System.Linq.Xml命名空间,XElementXAttribute两个延伸XObject,但它们各自分开地定义其属性Value,所以需要这种支化或使用dynamic类型。

在其他对象模型中,类似于@meganaut提供的类似场景中的泛型也可以使用。

相关问题