我有一个代表信用卡详细信息的类。为了表示有效期和到期月份和年份,我使用了四个类型的属性int
:
public int ValidFromMonth { get; set; }
public int ValidFromYear { get; set; }
public int ExpiresEndMonth { get; set; }
public int ExpiresEndYear { get; set; }
我正在对此类进行 XML 序列化以供第三方使用。如果值小于 10,该第三方要求我的月份和年份值以前导零作为前缀
<validFromMonth>02</validFromMonth>
<validFromYear>09</validFromYear>
<expiresEndMonth>10</expiresEndMonth>
<expiresEndYear>14</expiresEndYear>
.NET 是否支持将强制执行此规则的任何属性(或者我是否可以创建自定义属性),可能使用格式字符串(例如{0:00}
)?
注意:我知道我可以添加我自己string
的在内部进行格式化的[XmlIgnore]
属性,并向我的属性添加一个属性int
,但这感觉像是一个二流的解决方案。
编辑: 经过一番考虑,我想知道这是否真的不可行。序列化没有问题,但为了使反序列化工作,您需要取消格式化序列化字符串。在上面的简单示例中,这很容易,但我不确定它是否可以在更一般的情况下工作。
Edit2: 定义两位数要求的 XML 模式如下。
简单类型定义:
<xs:simpleType name="CreditCardMonthType">
<xs:annotation>
<xs:documentation>Two digit month</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:minLength value="2" />
<xs:maxLength value="2" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="CreditCardYearType">
<xs:annotation>
<xs:documentation>Two digit year</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:minLength value="2" />
<xs:maxLength value="2" />
</xs:restriction>
</xs:simpleType>
使用这些类型的信用卡定义:
<xs:attribute name="ExpiryMonth" type="CreditCardMonthType" use="required">
<xs:annotation>
<xs:documentation>Credit/debt card's expiry month.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="ExpiryYear" type="CreditCardYearType" use="required">
<xs:annotation>
<xs:documentation>Credit/debt card's expiry year.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="StartMonth" type="CreditCardMonthType" use="optional">
<xs:annotation>
<xs:documentation>Switch card's start month.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="StartYear" type="CreditCardYearType" use="optional">
<xs:annotation>
<xs:documentation>Switch card's start year.</xs:documentation>
</xs:annotation>
</xs:attribute>