dongyun6229 2009-06-27 17:58
浏览 51
已采纳

C#和PHP OOP的区别

I have a general OOP question.

If I have the following classes in C#

class Parent
{
    public string val = "Parent";

    public void getValue()
    {
        Console.WriteLine(this.val);
    }
}

class Child:Parent
{
    public string val = "Child";
}

Child child = new Child();
child.getValue();

The code outputs 'Parent'. As I understand it's because this points to Parent object, right?

If I do the same in PHP5:

class ParentClass {
public $val = 'parent';

    public function foo()
    {
        echo $this->val;
    }
}

class ChildClass extends ParentClass {
public $val = 'child';
}

$a = new ChildClass();
$a->foo();

The result will be 'child'.

Though if I change

public $val = 'parent'; 

to

private $val = 'parent';

then PHP will also show 'parent'. C# always return 'parent' with both public and private access modifiers.

Is there any reason for this? And which behavior is correct?

Any useful links to read will be highly appreciated!

Thank you!

  • 写回答

3条回答 默认 最新

  • doujia1904 2009-06-27 18:05
    关注

    There is no correct or incorrect behavior in your stated scenarios. The language designers did what made sense to them.

    The reason you don't get the expected behavior in c# is because GetValue is being called in the Parent class, where "this" means the parent val.

    To get the correct behavior, you would include the same method in the Child class, with the override keyword:

    public class Child
    {
        public string val = "Child";
        public override void GetValue()
        {
            Console.WriteLine(val);
        }
    }
    

    ...which would print "Child" to the console.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ROS Turtlebot3 多机协同自主探索环境时遇到的多机任务分配问题,explore节点
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题