C#的基本问题?

hwj383 2008-03-06 10:46:23
public class A
{
public void putstring()
{
MessageBox.Show("A");
}
}
public class B : A
{
public void putstring()
{
MessageBox.Show("B");
}
}

main()
{
B b = new A();
b.putstring();//输出什么?为什么?请详细点.........菜鸟............
}
...全文
143 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2008-03-07
  • 打赏
  • 举报
回复
不好意思,自已手工写的没有测试!
cheng_feng001 2008-03-07
  • 打赏
  • 举报
回复
楼上的不对,看我下面的测试程序:
程序1

using System;

namespace mytest
{
public class A
{
public virtual void Fun1(int i)
{
Console.WriteLine(i);
}
public void Fun2(A a)
{
a.Fun1(1);
Fun1(5);
}
}

public class B : A
{
public override void Fun1(int i)
{
base.Fun1(i + 1);
}
public static void Main()
{
B b = new B();
A a = new A();
a.Fun2(b);
b.Fun2(a);
}
}
}

运行结果:
2
5
1
6

程序2

using System;

namespace mytest
{
public class A
{
public virtual void Fun1(int i)
{
Console.WriteLine(i);
}
public void Fun2(A a)
{
a.Fun1(1);
Fun1(5);
}
}

public class B : A
{
public new void Fun1(int i)
{
base.Fun1(i + 1);
}
public static void Main()
{
B b = new B();
A a = new A();
a.Fun2(b);
b.Fun2(a);
}
}
}

运行结果:
1
5
1
5
北京的雾霾天 2008-03-07
  • 打赏
  • 举报
回复
ListBoxApp.aa是我的测试名称空间。

你给的代码是不能运行的。

对于名称相同的成员,在子类里不论使用不使用new都会覆盖父类的,只按本类型来执行。
北京的雾霾天 2008-03-07
  • 打赏
  • 举报
回复
输出的结果是:

警告 1 “ListBoxApp.aa.B.putstring()”隐藏了继承的成员“ListBoxApp.aa.A.putstring()”。如果是有意隐藏,请使用关键字 new。 D:\Projects\CSharp\ListBoxApp\ListBoxApp\Program.cs 32 16 ListBoxApp


错误 2 无法将类型“ListBoxApp.aa.A”隐式转换为“ListBoxApp.aa.B”。存在一个显式转换(是否缺少强制转换?) D:\Projects\CSharp\ListBoxApp\ListBoxApp\Program.cs 40 10 ListBoxApp
gxj760998 2008-03-07
  • 打赏
  • 举报
回复
B b = new A();
继承关系没有弄清楚哦
ILVCNET 2008-03-06
  • 打赏
  • 举报
回复
恩,我同意楼上的说法,如果你用类的多态性的话,你写的那个我还从来没见过,应该写成A b=new B();
根据你的要求我写了个简单的小程序如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace t1
{
class A
{
public void putstring()
{
Console.WriteLine("It is A");
}
}

class B:A
{
public void putstring()
{
Console.WriteLine("It is B");
}
}

class Program
{
static void Main(string[] args)
{
A b = new B();//利用类的多态性
b.putstring();
Console.ReadKey();
}
}
}

运行结果:
It is A
cnfixit 2008-03-06
  • 打赏
  • 举报
回复
如果是A b = new B();
那么应该输出A
原因是b的putstring方法这样的情况下相当于
public new void putstring()
{
MessageBox.Show("B");
}
那么在b实例的方法表中的putstring方法实际上是继承于A的putstring(B的putstring方法因为有new,所以排在后面)
所以是A
具体详细的可以去看看博客园的2007年度十佳里面anytao的系列文章
cnfixit 2008-03-06
  • 打赏
  • 举报
回复
B b = new A(); ?
A b = new B(); 吧

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧