在C#中的阴影和压倒一切的区别? [英] Difference between shadowing and overriding in C#?

查看:130
本文介绍了在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
}

然后当你调用这样的:

then when you call this:

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 <<<--
Console.WriteLine(((A)clB).Bar()); // output 1

假设你有一个基类,并使用在所有code,而不是继承的类的基类,并且使用的影子,它会返回值的基类的回报,而不是跟随的的ineritance树真正的对象的类型。

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 ineritance tree of the real type of the object.

希望我做的感觉:)

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

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