我在一些网站上看到了以下类型的场景..任何人都可以帮助我什么时候我们确实使用这种类型的场景......?
class emp
{
public void add()
{
MessageBox.Show("Emp class");
}
}
class dept : emp
{
public void disp()
{
MessageBox.Show("dept class");
}
}
emp ee = new dept();
我只是想知道我们何时创建这种类型的对象emp'ee = new dept()'而不是 'emp ee = new emp()' 谢谢, 希瓦
答案 0 :(得分:8)
上面的例子展示了继承。继承是一种“IS A”关系,在这种情况下,“dept”是一个“emp”,这意味着只要你的代码使用emp,它也应该能够使用dept对象。
为ee分配一个新部门,证明dept是一个emp,即使它可能会添加其他功能,例如disp方法。
答案 1 :(得分:2)
此处显示的过程称为继承。
基本上所做的是变量ee
的类型声明为emp
类型;这是合法的,因为类型dept
与emp
有一个is-a关系(大声说出来,就是“dept是一种emp”)。
当你想接受从emp继承的任何变量(由class dept : emp
声明表示)作为某种参数时,你可以这样做。
答案 2 :(得分:0)
你的意思是继承?如果这就是您的要求,您需要在object oriented programming in C#.
上找到一本书dept上的方法disp()没有理由。你可以去:
emp ee = new dept(); ee.add();
这将调用emp。
中的add()方法答案 3 :(得分:0)
这是显而易见的继承......
在继承中如果你想同时使用派生类方法和基类方法,你需要创建这个对象。
希望这是有帮助的
答案 4 :(得分:0)
如果你想同时使用派生类methoda以及基类方法,你需要创建这个对象。
答案 5 :(得分:0)
我们为运行时多态性做这件事。当我们需要调用派生类方法时,需要调用哪个派生类取决于基于用户输入的运行时。这是一个非常简单的例子:
static void Main(string[] args)
{
List<Shape> shapes = new List<Shape>();
shapes.Add(new Circle());
shapes.Add(new Square());
shapes.Add(new Rectangle());
foreach (Shape s in shapes)
s.Draw();
Console.Read();
}
public class Shape
{
public virtual void Draw() { }
}
public class Square : Shape
{
public override void Draw()
{
// Code to draw square
Console.WriteLine("Drawing a square");
}
}
public class Circle : Shape
{
public override void Draw()
{
// Code to draw circle
Console.WriteLine("Drawing a circle");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
// Code to draw circle
Console.WriteLine("Drawing a rectangle");
}
}
*****Output:
Drawing a circle
Drawing a square
Drawing a rectangle*****
在实际情况中,用户可能在运行时确定他想要绘制的形状。因此,在实现时,您可以创建一个Shape类的对象,并根据用户选择(在switch或if-else中)为其指定Circle,Rectangle或Square。当你调用Shape.Draw()时,它将调用适当的派生类方法。