Java 1.6的@覆盖相当于在C#中的接口 [英] Equivalent of Java 1.6 @Override for interfaces in C#

查看:113
本文介绍了Java 1.6的@覆盖相当于在C#中的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题给出了 Java的@覆盖有C#相当于覆盖关键字的方法的答案。然而,由于Java的1.6 @Override注释可以应用于接口还



这种情况的实际使用是在Java中你当一类声称它实现编译错误当它不再做接口方法(例如,如果接口方法被删除)。 ?是否有同样的功能在C#



某些代码示例:



Java的:

 公共接口A {
公共无效美孚();
//公共无效巴(); //删除方法。
}

公众B类实现A {
@覆盖公共无效美孚();
@覆盖公共无效巴(); //编译错误
}



C#:

 公共接口IA {
无效美孚();
//空栏(); //删除方法。
}

公共B类:A {
公众覆盖无效美孚(); //不能编译不压倒一切的方法
公共无效酒吧(); //编译,但不再实现接口方法
}


解决方案

有是的类似的功能:显式接口实现

 公共接口IA {
无效美孚();
//空巴(); //删除方法。
}

公共B类:IA {
无效IA.foo(){}
无效IA.bar(){} //不能编译
}

的问题是,如果你这样做,你不能调用通过<$ c中的方法$ C>这个指针(从类中),或通过计算结果为一个表达式 B - 这是现在有必要转换为 IA



您可以解决,通过使具有相同签名的公共方法和转发调用明确实施像这样:

 公共b类:IA {
无效IA.foo(){this.foo() ; }
公共无效美孚(){}
}



然而,这不是个ŧ比较理想,而且我从来没有见过它在实践中完成。


This question gives the answer that Java's @Override has the C# equivalent of the override keyword on methods. However, since Java 1.6 the @Override annotation can be applied to interfaces also.

The practical use for this is that in Java you get compile errors when a class claims it implements an interface method when it no longer does (e.g. if the interface method is removed). Is there equivalent functionality in C#?

Some code examples:

Java:

public interface A {
  public void foo();
  // public void bar(); // Removed method.
}

public class B implements A {
  @Override public void foo();
  @Override public void bar(); // Compile error
}

C#:

public interface IA {
  void Foo();
  // void Bar(); // Removed method.
}

public class B : A {
  public override void Foo(); // Doesn't compile as not 'overriding' method
  public void Bar(); // Compiles, but no longer implements interface method
}

解决方案

There is similar functionality: explicit interface implementation.

public interface IA { 
  void foo(); 
  // void bar(); // Removed method. 
} 

public class B : IA { 
  void IA.foo() {}
  void IA.bar() {} // does not compile
} 

The problem is that if you do this you cannot call the methods through the this pointer (from inside the class) or through an expression that evaluates to a B -- it is now necessary to cast to IA.

You can work around that by making a public method with the same signature and forwarding the call to the explicit implementation like so:

public class B : IA { 
  void IA.foo() { this.foo(); }
  public void foo() {}
} 

However this isn't quite ideal, and I 've never seen it done in practice.

这篇关于Java 1.6的@覆盖相当于在C#中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆