我想從具有兩個擴展公共complexType的complexType的XSD生成代碼。繼承者有一個名爲「value」的公共屬性,它有不同的類型。由於XSD規則,我無法將其放在我的基本類型上。我的目的是多態地調用基類型的屬性,這將調用子類的正確方法。這可能嗎?在代碼生成(通過xsd.exe)類中調用子類屬性
這裏是我的XSD
<xs:complexType name="Property">
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="StringProperty">
<xs:complexContent>
<xs:extension base="Property">
<xs:attribute name="value" type="xs:string" use="required"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="BooleanProperty">
<xs:complexContent>
<xs:extension base="Property">
<xs:attribute name="value" type="xs:boolean" use="required"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
這將生成以下代碼:
public partial class Property {
private string nameField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
}
public partial class StringProperty : Property {
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
public partial class BoolProperty : Property {
private bool valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
這裏就是我想要做的:
// ConfigProperties is an array of Property objects
foreach (Property property in config.ConfigProperties)
{
// Doesn't compile since Property.value doesn't exist in the base class.
Console.WriteLine(property.value);
}
我試圖實現一個 「值」 Property對象上的getter屬性希望子類的「value」屬性定義可以隱藏它,但事實並非如此這樣的伎倆:
public partial class Property
{
public virtual string value
{
get { throw new NotImplementedException(); } // this method is called instead of the Property subclass methods
}
}
後續問題編輯:這些問題的答案證實了我的擔心,這是不可能的。它仍然會是可能的,雖然做以某種方式如下:
foreach (Property property in config.ConfigProperties)
{
somevalue = property.GetValue();
}
其中的GetValue()是計算出的方法是什麼返回類型應該憑藉它實際上是使用屬性的子類的有哪些?請原諒我非常懶惰。我被給予相信it's a virtue。 =)
我猜測一樣多。如果沒有擴展和覆蓋的XSD限制,我認爲這會更容易。謝謝你! – Jeremy 2009-12-17 15:55:03