这里怎么只能访问类方法? [英] How here only A class method is accessible ?
本文介绍了这里怎么只能访问类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
namespace ConsoleApplication1
{
class A
{
public void Amethod()
{
Console.WriteLine("Amethod");
}
}
class B : A
{
public new void Bmethod()
{
Console.WriteLine("Bmethod");
}
}
class Program
{
static void Main()
{
A ref2 = new B();
ref2.Amethod(); // how here only A class method is accessible ? Please explain
B ref3 = new B();
ref3.Amethod();
ref3.Bmethod();
}
}
}
在上面的代码中,如何才能访问A类方法?请解释。
In the above code, how here only A class method is accessible? Please explain.
推荐答案
因为您的变量ref2
被声明为类型A,编译器将只访问A类属性和方法 - 因为尽管你在这种情况下为它分配了一个B实例,ref2
不是一个B.它包含一个B实例,因为你没有改变它,但这可能不会持久。
您可以随意将其更改为A类实例。
有点儿喜欢去购物:A是蔬菜,B是胡萝卜 - 因为胡萝卜是一种蔬菜,你可以把蔬菜放在你的购物清单上,然后带着胡萝卜回来。但你也可以带回土豆,因为那也是一种蔬菜。但是马铃薯不具有胡萝卜所具有的橙色特性,所以你不能说蔬菜有橙色。
Because your variableref2
is declared as a type A, the compiler will only access A class properties and methods - because despite you assigning a B instance to it in this case,ref2
is not a B. It contains an instance of B, because you don't change it, but that may not last.
You are perfectly at liberty to change it later to a A class instance.
It's a bit like going shopping: is A is Vegetable and B is Carrot - because a Carrot is a type of Vegetable you can put "Vegetable" on your shopping list and come back with a Carrot. But you could also come back with a Potato, because that is also a Vegetable. But Potato does not have the "Orange colour" property that Carrot does, so you can't say "Vegetable has Orange colour".
这篇关于这里怎么只能访问类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文