【问题标题】:list all properties with [XmlAttribute] of given class列出给定类的 [XmlAttribute] 的所有属性
【发布时间】:2016-04-20 18:27:55
【问题描述】:

例如我有一个简单的类

class SomeCfg
{
    [XmlAttribute("ArchivePath")]
    public string ArchivePath { get; set; }
}

可以看出,给定的类有一个带有 XmlAttribute 的属性。但是当程序执行到那个代码时

 var t = typeof (SomeCfg);
 var props = t.GetProperties().Where(
    prop => Attribute.IsDefined(prop, typeof(XmlAttribute)));

运行时抛出异常

System.ArgumentException: Type passed in must be derived from System.Attribute or System.Attribute itself.

当然,当我看到类型层次结构时,我意识到这是真的(我不会解释为什么它不继承自该类)。

我的问题是如何列出这些属性(在这种情况下,不能创建一个继承自 XmlAttribute 和 System.Attribute 的类)。

根据问题标签.Net版本是4.0。

【问题讨论】:

  • 对不起,这条线当然不见了。我更正了这个问题。

标签: c# .net-4.0


【解决方案1】:

您是否可以使用System.Xml.XmlAttribute 而不是System.Xml.Serialization.XmlAttributeAttribute

System.Xml.XmlAttribute 用于表示来自 xml 文档的属性。 System.Xml.Serialization.XmlAttributeAttribute 指定 XmlSerializer 必须将类成员序列化为 XML 属性。

【讨论】:

  • 是的,属性查询的行应该是这样的 var props = t.GetProperties().Where( prop => Attribute.IsDefined(prop, typeof(XmlAttributeAttribute)))
【解决方案2】:

您可以从以下代码中获取包含 XMLAttribute 的属性..

var props = t.GetProperties()
             .Where(prop =>
                 prop.GetCustomAttributes(typeof(XmlAttributeAttribute), false).Any(PropType => PropType.GetType() == typeof(XmlElementAttribute) ||
                                                         PropType.GetType() == typeof(XmlAttributeAttribute)));

如果您不想使用完整的 LINQ,那么这篇文章对您也有帮助。

Serialize all properties in a class as attributes instead of elements

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    相关资源
    最近更新 更多