为什么Java和C#中哎呀有什么不同? [英] Why does Java and C# differ in oops?

查看:160
本文介绍了为什么Java和C#中哎呀有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1)为什么下面的代码不同。



C#:



<预类=郎-CS prettyprint -override> Base类
{
公共无效美孚()
{
的System.Console.WriteLine(基地);
}
}

类派生:基本
{
静态无效的主要(字串[] args)
{
底b =新基地();
b.foo();
B =新派生的();
b.foo();
}
公开新无效美孚()
{
的System.Console.WriteLine(派生);
}
}



Java的:



<预类=郎-java的prettyprint-覆盖> 类基地{
公共无效美孚(){
的System.out.println(基地);
}
} $ B派生
$ B类扩展基地{
公共无效美孚(){
的System.out.println(派生);
}

公共静态无效的主要(字串[] S){
基地B =新基地();
b.foo();
B =新派生的();
b.foo();
}
}



2)当从一种语言迁移到另一个是什么我们需要的东西,以确保平稳过渡。


解决方案

究其原因是,在Java中,方法是虚拟默认情况下。在C#中,虚方法必须明确标记为这种结果
下面的C#代码等同于Java代码 - 注意使用虚拟在在派生类的基类和覆盖

  Base类
{
公共虚拟无效美孚()
{
的System.Console.WriteLine(基地);
}
}

类派生
:基本
{
静态无效的主要(字串[] args)
{
底b =新基地();
b.foo();
B =新派生的();
b.foo();

}

公众覆盖无效美孚()
{
的System.Console.WriteLine(派生);
}
}

您发布的C#代码隐藏方法在类导出。这是你通常不希望这样做,因为它会导致继承问题的东西。



使用您发布,类下面的代码将输出不同的东西,虽然它总是相同的实例:

 基地b =新派生的(); 
b.foo(); //写基地
((衍生)B)包含.foo(); //写派生出来的



我上面将输出导出,在这两种情况下提供的固定码。


1) Why does the following codes differ.

C#:

class Base
{
  public void foo()
  {
     System.Console.WriteLine("base");
  }
}

class Derived : Base
{
  static void Main(string[] args)
  {
    Base b = new Base();
    b.foo();
    b = new Derived();
    b.foo();
  }
  public new void foo()
  {
    System.Console.WriteLine("derived");
  }
}

Java:

class Base {
  public void foo() {
    System.out.println("Base");
  }  
}

class Derived extends Base {
  public void foo() {
    System.out.println("Derived");
  }

  public static void main(String []s) {
    Base b = new Base();
    b.foo();
    b = new Derived();
    b.foo();
  }
}

2) When migrating from one language to another what are the things we need to ensure for smooth transition.

解决方案

The reason is that in Java, methods are virtual by default. In C#, virtual methods must explicitly be marked as such.
The following C# code is equivalent to the Java code - note the use of virtual in the base class and override in the derived class:

class Base
{
    public virtual void foo()
    {
        System.Console.WriteLine("base");
    }
}

class Derived
    : Base
{
    static void Main(string[] args)
    {
        Base b = new Base();
        b.foo();
        b = new Derived();
        b.foo();

    }

    public override void foo()
    {
        System.Console.WriteLine("derived");
    }
}

The C# code you posted hides the method foo in the class Derived. This is something you normally don't want to do, because it will cause problems with inheritance.

Using the classes you posted, the following code will output different things, although it's always the same instance:

Base b = new Derived();
b.foo(); // writes "base"
((Derived)b).foo(); // writes "derived"

The fixed code I provided above will output "derived" in both cases.

这篇关于为什么Java和C#中哎呀有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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