有人请解释一下 [英] some one please explain this
问题描述
朋友,
任何人都可以给我这个程序的解释吗?
在Java中的输出:
Hi Friends,
Can anyone give me a explnation for this program??
in Java the output :
Hi From derived
在C#中的输出:
in C# the Output :
Hi From base
为什么两种语言都会混淆概念?
但是用两种语言-对象类型是派生类
Why oops concept diffrent in both langauges ?
but in both language - the object type is derived class
class Program
{
static void Main(string[] args)
{
MyClass A= new MyClass1();
A.h1();
System.Type type = A.GetType();
Console.WriteLine(type.ToString());
}
}
public class MyClass
{
public void h1()
{
Console.WriteLine("Hi From base");
}
}
public class MyClass1 :MyClass
{
public void h1()
{
Console.WriteLine("Hi From derived");
}
}
推荐答案
如果要在派生类中重写该方法,则需要在基类中将其标记为虚方法.
If you want the method to be overridden in a derived class you need to mark it as virtual in the base.
public class MyClass
{
public virtual void h1()
{
Console.WriteLine("Hi From base");
}
}
public class MyClass1 :MyClass
{
public override void h1()
{
Console.WriteLine("Hi From derived");
}
}
有了它,您的MyClass A实例就只知道它包含的h1方法.
As you have it your instance of MyClass, A, only knows of the h1 method it contains.
请首先解决警告!每个警告都可能是一个问题.
现在您遇到了一个隐藏的问题.
我猜您在编译C#时发出了警告,对吧?
IIRC在Java中都是虚拟的,而在C#中只有这样声明的方法.
(不过,我不是Java程序员)
这是在Visual Studio 2010中针对C#的警告:
Fix the warnings first! Each warning might be a problem.
And you run now into a hiding issue.
I guess you had a warning while you did compile C#, right?
IIRC, in Java, all is virtual, while in C# only the so declared methods are.
(I''m not a Java programmer, though)
This is the warning you get for C# in Visual Studio 2010:
Warning 1 'ConsoleApplication1.MyClass1.h1()' hides inherited member 'ConsoleApplication1.MyClass.h1()'. Use the new keyword if hiding was intended.
但是我必须承认:在警告上按Visual Studio 2010中的F1以获取有关它的更多详细信息时,来自Microsoft的帮助文本简直就是废话.没有关于虚拟/覆盖的消息.没有给出最简单的解决方案:重命名隐藏成员,也没有给出有关虚拟/覆盖的任何信息...
我会说:没有人"想要隐藏成员-要求维护麻烦.
为什么有人会通过应用new
关键字想要隐藏隐藏成员?
?
[/EDIT]
But I have to admit: when pressing F1 in Visual Studio 2010 on that warning to get more details on it, the help text from Microsoft is crap. No word about virtual/override. The simplest solution is not given: rename the hiding member, nor any word about virtual/overriding is given...
I would say: "no one" ever wants to hide a memeber - calls for maintenance trouble.
Any example why one would want to hide a member by applying the new
keyword?
[/EDIT]
这篇关于有人请解释一下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!