在方法中传递子类对象 [英] Passing subclass object in method
本文介绍了在方法中传递子类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A {}
class B:A {}
class C
{
public void fun(A obj)
{
Console.WriteLine( Hello);
}
静态 void Main( string [] args)
{
C ob = new C();
B bObject = new B();
ob.fun(bObject);
}
}
在这个程序中,Formal Parameter是'A'的对象,而实际的Parameter是对象'B'的子类是'A'的子类。这是工作。我只需要解释。
解决方案
B不是A的子类,B是继承自A类。
这意味着B类实际上是一个具有更多属性,方法等的A类...
< span class =code-keyword> class A
{
protected void SayHello();
}
class B:A
{
public void SayGoodbye();
}
objA = new A();
B objB = new B();
你可以使用:
objB.SayHello();
objB.SayGoodbye();
但你可以' t使用:
objA.SayGoodbye (); 跨度>
class A { }
class B : A { }
class C
{
public void fun(A obj)
{
Console.WriteLine("Hello");
}
static void Main(string[] args)
{
C ob = new C();
B bObject = new B();
ob.fun(bObject);
}
}
In this program, Formal Parameter is object of 'A' and actual Parameter is object of 'B' that is subclass of 'A'. it is working. I need just explanation.
解决方案
B isn't a subclass of A, B is inherited from class A.
That means that B class is in fact an A class with more properties, methods, etc...
class A { protected void SayHello(); } class B : A { public void SayGoodbye(); } A objA = new A(); B objB = new B(); you can use: objB.SayHello(); objB.SayGoodbye(); but you can't use: objA.SayGoodbye();
这篇关于在方法中传递子类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文