跨多个属性的XMLSerialize CategoryAttribute

时间:2011-11-18 01:54:43

标签: c# visual-studio xml-serialization

C#.net 2008

我正在处理一个类文件,该文件在大约8个序列化类别中有几百个属性。 目前看起来像这样:

[CategoryAttribute("Group1")]
public string property
[CategoryAttribute("Group1")]
public string property
[CategoryAttribute("Group1")]
public string property
[CategoryAttribute("Group1")]
public string property

[CategoryAttribute("Group2")]
public string property
[CategoryAttribute("Group2")]
public string property
[CategoryAttribute("Group2")]
public string property
[CategoryAttribute("Group2")]
public string property

我以前做过研究,并没有找到解决方案的任何导致所以这次我问是否有人有解决办法让事情变得不那么混乱? 如:

[CategoryAttribute("Group1")]
{
public string property;
public string property;
public string property;
public string property;
public string property;
public string property;
public string property;
}
[CategoryAttribute("Group2")]
{
public string property;
public string property;
public string property;
public string property;
public string property;
public string property;
public string property;
}

3 个答案:

答案 0 :(得分:3)

虽然所有其他答案都完全正确,但我可以向你提出另一个想法。

您可以尝试使用T4模板生成此类文件。 请在GitHub

上查看我的示例

基本上我创建了一个模板/EntitiesWithALotOfProperties/FirstClass.generated.tt,它读取一个名称相同的文件,但替换为“。generated.tt”“。template.cs”并根据你的逻辑处理后者。

重要的是要注意:FirstClass.template.cs应该将构建操作设置为“”。这个想法是:* .cs文件可以使用ReSharper轻松编辑(基本上有IntelliSense),但同时,它不会声明重复的成员。

以下是一些截图: Another partial part Template file Generated file

答案 1 :(得分:2)

没有。不会将属性附加到像这样的项目组。如果每个类中确实有数百个属性,则可能需要考虑重新组织类。每个小组都可以上课吗?这些复杂的业务对象,或类别是否可以成为包含其中属性的字典对象?只是一些想法。

答案 2 :(得分:0)

您可以考虑编写一个自定义类型描述符,为其各种成员公开ICustomAttributeProvider。虽然这并不难实现,但我发现.NET中的类型描述符发现略有破坏。大多数框架函数都能识别它们,但其他框架函数不会识别它们,而只是使用GetType()。GetProperty()代替(例如WCF DataServiceContext)。

我建议您坚持使用当前的方法,但我会将类别名称设置为const(属性值必须是常量),因此您可以在一个位置更改它。如果你需要帮助实现类型描述符让我知道,我相信我可以拿出一个例子。看看MSDN中的TypeDescriptor,TypeDescriptorProvider和PropertyDescriptor类,你必须非常小心,特别是对于如此庞大的类(并且通常你不仅仅有属性上的CategoryAttribute,它要求你混合内置的类型描述符和你的自定义)。