我在两个类中做完全相同的事情,其中一个编译器允许它正常运行,但另一个却给我一个错误。为什么双重标准?有 15 个类使用相同的模式,但只有一个类拒绝编译,并提示以下错误:
'AWWAInvoicingXML.AwwaTransmissionInfo' does not implement interface member 'AWWAInvoicingXML.IXmlSerializable.fromXML(System.Xml.XmlDocumentFragment)'. 'AWWAInvoicingXML.AwwaTransmissionInfo.fromXML(System.Xml.XmlDocumentFragment)' is either static, not public, or has the wrong return type.
这是我的源代码...如果我注释掉 AwwaTransmissionInfo 类,文件的其余部分编译得很好,所以我知道它不是那些编译器在第一个错误后就死掉的代码。我知道,我知道,我在这里尝试做的事情有内置的东西,但假设我真的知道我在做什么,并且出于某种原因跳过了内置的序列化程序:)
public interface IXmlSerializable {
//if this interface is implemented, the object can be serialized to XML
string toXML();
IXmlSerializable fromXML(XmlDocumentFragment inXml);
}
public class AwwaTransmissionInfo : IXmlSerializable {
public DateTime DateTime = DateTime.Now;
public int ItemCount;
public string toXML() {
throw new Exception("The method or operation is not implemented.");
}
public AwwaTransmissionInfo fromXML(XmlDocumentFragment inXml) {
throw new Exception("The method or operation is not implemented.");
}
}
public class CEmail {
public string Email = "";
public string toXML() {
throw new System.Exception("The method or operation is not implemented.");
}
public CEmail fromXML(XmlDocumentFragment inXml) {
throw new System.Exception("The method or operation is not implemented.");
}
}
最佳答案
问题在于方法签名必须与接口(interface)完全匹配。
最简单的解决办法就是改变
public AwwaTransmissionInfo fromXML(XmlDocumentFragment inXml) {
到
public IXmlSerializable fromXML(XmlDocumentFragment inXml) {
如果您对此不满意,可以显式实现该接口(interface)。添加这个:
public IXmlSerializable IXmlSerializable.fromXML(XmlDocumentFragment inXml) {
return this.fromXML(inXml);
}
然后您将有两个 fromXML() 定义,一个用于作为类的实例调用时使用,一个用于通过接口(interface)调用时使用。
关于C#双重标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/493841/