C#中阴影和覆盖的区别? [英] Difference between shadowing and overriding in C#?

查看:26
本文介绍了C#中阴影和覆盖的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 中阴影覆盖方法有什么区别?

What's difference between shadowing and overriding a method in C#?

推荐答案

继承...

假设你有这个类:

class A {
   public int Foo(){ return 5;}
   public virtual int Bar(){return 5;}
}
class B : A{
   public new int Foo() { return 1;}     //shadow
   public override int Bar() {return 1;} //override
}

然后当你调用它时:

A clA = new A();
B clB = new B();

Console.WriteLine(clA.Foo()); // output 5
Console.WriteLine(clA.Bar()); // output 5
Console.WriteLine(clB.Foo()); // output 1
Console.WriteLine(clB.Bar()); // output 1

//now let's cast B to an A class
Console.WriteLine(((A)clB).Foo()); // output 5 <<<-- shadow
Console.WriteLine(((A)clB).Bar()); // output 1

假设你有一个基类并且你在所有代码中都使用基类而不是继承的类,并且你使用影子,它将返回基类返回的值而不是遵循真实类型的继承树对象.

Suppose you have a base class and you use the base class in all your code instead of the inherited classes, and you use shadow, it will return the values the base class returns instead of following the inheritance tree of the real type of the object.

在此处运行代码

希望我说得有道理:)

这篇关于C#中阴影和覆盖的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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