C#序列化中类的属性的别名

时间:2014-06-09 07:50:28

标签: c#-4.0 serialization

有没有办法在C#中为class的属性设置别名。

由于属性定义名称可能太长,我认为别名在序列化方面更好,因此文件大小会减少。

这可能在c#中吗?

请告知,任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:0)

是的,尝试XmlType用于类型,XmlElement和XmlAttribute用于属性。

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmltype(v=vs.110).aspx

[XmlType("foo")]
class FooReallyLongName {

    public FooReallyLongName() {}

    [XmlElement("bar")]
    public BarReallyLongName { get; set; }
}

对于Json,请尝试对手:http://james.newtonking.com/json/help/index.html?topic=html/SerializationAttributes.htm

或者如果您使用数据合约属性,Newtonsoft.Json也会尊重它们:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute

摘自MSDN:

[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person : IExtensibleDataObject
{