没有得到继承的概念 [英] Not getting Inheritance concept
问题描述
1。为什么我无法访问S类方法。
2.为什么我能在M级创建同名的方法
public class S
{
公开 S()
{
}
public int myFunc( int a, int b)
{
return a + b;
}
}
public class M: S
{
public M()
{
}
public string myFunc( int a, int b)
{
return (a + b).ToString();
}
}
public class 测试
{
public static void Main ( string [] args)
{
M mm = new M() ;
mm.myFunc( 1 , 2 ); // 为什么我无法访问S class myFunc
}
}
Quote:1。为什么我无法访问S类方法。
你实际上可以。
因为,通过非常继承的概念,M
是S
,你可以打电话。
然而,M :: myFunc
隐藏S :: myFunc
,所以你需要一个解决方法,例如:
int k =(mm as S).myFunc( 1 , 2 跨度>);
Quote:2。为什么我能够在类M中创建具有相同名称的方法
因为编译器(不情愿地:-))允许这样做。但是,如果实际上是你的意图阴影,那么你最好使用
new
通知(如已经建议的)编译器本身。
< blockquote>首先,如果在父类和子类中都有相同签名的方法,则必须使用new关键字。您无法访问S myFucntion,因为当您实例化像
M mm = new M(); $ p $这样的对象时p>
这意味着你指的是M类,如果在父类和子类中都有相同签名的方法,那么它取决于你创建的是哪个对象?将您的代码更改为
S mm = new S();
你可以调用s myFunc。
1. Why I am not able to access S class method.
2. And why am I able to create the method with the same name in class M
public class S
{
public S()
{
}
public int myFunc(int a, int b)
{
return a + b;
}
}
public class M:S
{
public M()
{
}
public string myFunc(int a, int b)
{
return (a + b).ToString();
}
}
public class Test
{
public static void Main(string[] args)
{
M mm = new M();
mm.myFunc(1,2); // Why I am not able to access S class myFunc
}
}
解决方案 Quote:1. Why I am not able to access S class method.
You actually can.
Since, by the very inheritance concept, M
is S
, you may call it.
However, M::myFunc
hides S::myFunc
, so you need a workaround, e.g.:
int k = (mm as S).myFunc(1,2);
Quote:2. And why am I able to create the method with the same name in class M
Because the compiler (reluctantly :-) ) allows that. However, if shadowing the method is really your intention, then you'd better inform (as already suggested) the compiler itself using new
.
first of all you must use "new" keyword when you have method with same signature in both parent and child classes. you are not able to access S myFucntion because when you instantiate an object like M mm = new M();
that's mean you are pointing to M class, if the method with same signature is available in both parent and child classes then it depends on which object you are creating? change your code to
S mm = new S();
and you will be able to call s myFunc.
这篇关于没有得到继承的概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!