C#双重标准?

标签 c# interface

我在两个类中做完全相同的事情,其中​​一个编译器允许它正常运行,但另一个却给我一个错误。为什么双重标准?有 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/

相关文章:

c# - 在 C# 中如何使用 switch 语句检查 int 类型是否为空?

Typescript Unions 接口(interface)和原语

JAVA:与接口(interface)的实现相比,InvocationHandler 有哪些优势?

c# - 如何在从 asp.net c# 中的另一个下拉列表中选择项目后将项目加载到下拉列表中

c# - 强制 float 的误差相对较小

c# - 在 Windows 上获取给定路径的可用磁盘空间

java - 接口(interface)如何执行操作

javascript - 在 ES6 之前的 Typescript 中实现 Iterator<T> 的推荐方法

c# - 在接口(interface)中实现委托(delegate)

c# - 编辑 GridView 时显示下拉列表