本文介绍了关于C#中的对象创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用像这样的父类创建子类的对象:

manager obj =新员工,如果是,那么它需要在哪里?以及如何在内存级别实现

感谢您的回复



我尝试了什么:



i是C#和oops的新手。这是我第一次遇到c#而且用c#只用了15天所以请帮我学习

can i create object of child class using parent class like this:
manager obj=new employee if yes then where is it needed? and how at memory level it is implemented
thank u for response

What I have tried:

i am new to C# and oops . this is my first encounter with c# and it has been just 15 days with c# so help me to learn

推荐答案


class Employee
   {
   string Name {get; set;}
   int EmployeeNumber {get; set;}
   Employee ReportsTo {get; set;}
   }
class Manager : Employee
   {
   Car CompanyCar {get; set;}
   }



然后你可以愉快地说:


And then you can happily say:

Employee emp = new Manager();

因为经理是员工的超集 。

然后您可以访问任何员工属性:

Becuase a Manager is a "superset" of an employee.
You can then access any Employee properties:

Employee emp = new Manager();
...
Console.WriteLine(emp.Name);

但是......因为emp可以包含任何员工,你无法访问任何Manager特定的方法属性通过它。

But...because emp can contain "any employee" you can't access any Manager specific properties of methods via it.

Manager man new Manager();
Employee emp = man;
...
Console.WriteLine(emp.Name);
Console.WriteLine(man.CompanyCar);



但你不能这样做:


But you can't do this:

Manager man = new Employee(); 

因为Employee没有任何特定于Manager的方法属性:在这种情况下,因为Employee没有获得CompanyCar,而Managers则没有。

Because an Employee does not have any of the Manager specific properties of methods: in this case because an Employee does not get a CompanyCar, while Managers do.



这篇关于关于C#中的对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:53
查看更多