【发布时间】:2010-12-27 16:52:04
【问题描述】:
我正在尝试从具有两个扩展通用 complexType 的复杂类型的 XSD 生成代码。继承者有一个名为“value”的公共属性,它有不同的类型。当然,由于 XSD 规则,我不能把它放在我的基本类型上。我的意图是多态地调用基类型上的属性,这将调用子类上的正确方法。这可能吗?
这是我的 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 属性,希望子类的“值”属性定义能够隐藏它,但这并不能解决问题:
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() 是一种方法,它通过它实际使用的 Property 的子类来确定它应该具有什么返回类型?请原谅我非常懒惰。我相信it's a virtue。 =)
【问题讨论】:
标签: c# xsd code-generation