簡體   English   中英

跨多個屬性的XMLSerialize CategoryAttribute

[英]XMLSerialize CategoryAttribute across multiple properties

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;
}

盡管所有其他答案都是完全正確的,但我可以向您提出另一個想法。

您可以嘗試使用T4模板生成此類文件。 請在GitHub上查看我的示例

基本上,我創建了一個模板/EntitiesWithALotOfProperties/FirstClass.generated.tt ,該模板讀取具有相同名稱的文件,但將“ .generation.tt”替換為“ .template.cs”,並根據您的邏輯處理后者。

需要注意的重要事項: FirstClass.template.cs應該將構建操作設置為“ None ”。 這個想法是:* .cs文件可以使用ReSharper(基本上具有IntelliSense)輕松地進行編輯,但是同時,它不聲明重復的成員。

以下是一些屏幕截圖: 另一部分模板文件生成的文件

否。不會將屬性附加到此類項目組。 如果每個類中確實有數百個屬性,則可能需要考慮重新組織類。 每個小組都可以成為一個班嗎? 這些是復雜的業務對象,還是類別可以變成包含其中屬性的字典對象? 只是一些想法。

您可能會考慮編寫一個自定義類型描述符,該類型描述符針對其各種成員公開ICustomAttributeProvider。 盡管實現起來並不難,但是我發現.NET中的類型描述符發現有些破損。 大多數框架功能都可以識別它們,但其他功能則不能,只能使用GetType()。GetProperty()(例如WCF DataServiceContext)。

我建議您堅持使用當前的方法,但是我會將類別名稱設為某個常量(屬性值必須為常量),以便可以在一個位置進行更改。 如果您在實現類型描述符方面需要幫助,請告訴我,我敢肯定我可以舉一個例子。 看一下MSDN中的TypeDescriptor,TypeDescriptorProvider和PropertyDescriptor類,您必須特別小心,尤其是對於這么大的類(通常,您不僅在屬性上具有CategoryAttribute,而且還需要混合使用內置的type-descriptor和您的自定義對象)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM