【发布时间】:2014-02-14 18:25:37
【问题描述】:
MyObject 类的每个字段我都需要一个非常具体的格式
public class MyObject{
public Long Amount {get; set}
public Long FiscalAmount {get; set;}
// .... A lot more of fields
}
例如,
- 如果
MyObject.Amount为5000,则预期结果为00005000。 - 如果
MyObject.FiscalAmount为 23,则预期结果为 000023
为了实现这一点,我定义了一个 XML 文件:
<FieldDescriptionXML>
<FielDefinition>
<Name>Amount</Name>
<FillWith>0</FillWith>
<Lenght>8</Lenght>
</FielDefinition>
<FielDefinition>
<Name>FiscalAmount</Name>
<FillWith>0</FillWith>
<Lenght>6</Lenght>
</FielDefinition>
.... A lot more of fields
<FieldDescriptionXML>
然后我使用以下代码来获取具有所需输出的MyObject 字段
MyObject myObject = new MyObject();
myObject.Amount = 5000;
...
// Gets the xml definition
// I deserialize the previous XML file and name it FieldDescription
List<FieldDescription> fieldDescriptionList = DeserializeXML(XMLFilePath);
FieldDescription fieldDescription = fieldDescriptionList.Find(x => x.Name == "Amount");
// Apply the field definition and returns a string.
// For this I use a private method called ApplyXMLFielDefinition
// where I got how many spaces the result should be filled
string result = ApplyXMLFielDefinition(myObject.Amount,fieldDescription);
Console.Writeline(result) // prints 00005000
// Now same code for MyObject.FiscalAmount
如你所见,我得到了想要的输出,但我不得不一一重复代码。
还有其他更好的方法可以分享吗?谢谢。
环境:C# 4.0
【问题讨论】:
-
什么是
FieldDescription?ApplyXMLFielDefinition是什么? -
FieldDescription是序列化的xml文件。在ApplyXMLFielDefinition中,我使用FieldDescription值来为myObject.Amount提供所需的格式。在这种情况下,它所做的是用四个零填充值 5000。 -
显示方法,而不是描述它们的作用......并且序列化的xml文件没有任何意义。大概应该反序列化,重要的部分是:反序列化成什么?
-
FieldDescription 是一个 List
吗?表示类列表
标签: c# xml linq xml-serialization