C# 为什么我们能够从派生类-C的构造函数调用interface.ctor[base()
代码如下:C# 为什么我们能够从派生类-C的构造函数调用interface.ctor[base(),c#,inheritance,interface,C#,Inheritance,Interface,代码如下: namespace ClassLibrary1 { public class Manager : IEmployee { private int _empId; private string _empName; private string _location; public int EmpId { get {
namespace ClassLibrary1
{
public class Manager : IEmployee
{
private int _empId;
private string _empName;
private string _location;
public int EmpId
{
get
{
return _empId;
}
set
{
_empId = value;
}
}
public string EmpName
{
get
{
return _empName;
}
set
{
_empName = value;
}
}
public string Location
{
get
{
return _location;
}
set
{
_location = value;
}
}
public Manager(int empId, string empName, string Location)
: base()
{
this._empId = empId;
this._empName = empName;
this._location = Location;
}
public string GetHealthInsuranceAmount()
{
return "Additional Health Insurance Premium Amount is: 1000";
}
}
}
在这里,类管理器实现了接口IEmployee。接口不应该有构造函数。
那么,经理构造函数如何能够调用IEEmployee构造函数呢
以下是IEEmployee界面:
以下是调用程序:
using ClassLibrary1;
using System;
namespace InheritanceExample
{
class Program
{
static void Main(string[] args)
{
IEmployee emp;
emp = new Manager(1001, "Vikram", "USA");
Console.WriteLine($"Managers EmpId: {emp.EmpId}. Name: {emp.EmpName}. Location: {emp.Location}");
Console.WriteLine($"Manager's health insurance: {emp.GetHealthInsuranceAmount()}");
//emp = new SalesMan(1002,"Sukhmeet","Austrailia");
//Console.WriteLine($"SalesMan EmpId: {emp.EmpId}. Name: {emp.EmpName}. Location: {emp.Location}");
//Console.WriteLine($"SalesMan's health insurance: {emp.GetHealthInsuranceAmount()}");
}
}
}
如上所示,Manager类构造函数调用IEEmployee接口构造函数的方式如下:
请看:我使用的是C语言版本7.3.Net Framework 4.8,但这并不重要。C中的每个类都派生自对象基类 C在类继承和接口实现中使用了相同的关键字:符号,这一事实可能让您感到困惑 当您调用:base时,您没有调用接口的构造函数。它没有。您正在调用System.object的构造函数,它是一个没有参数的简单构造函数
尝试删除接口,看看它是否仍然有效。删除接口实现,你会看到基本接口仍然有效。这是因为它属于对象,而不是接口。除了对象之外,.NET中的所有类都从一个类派生。若一个类并没有声明基类,那个么它直接从object派生。你的IEmployee不是一个类,也没有涉及到这个问题。我认为这个问题源于一个错误的假设,即实现接口的类是一个派生类。不是。它是一个实现接口的类,但它是一个派生类;它是从System.Object类派生出来的,这就是为什么:base有效,@Camilo我明白你的意思,但这可能会混淆OP.@41686d6564我不同意。OP已经被弄糊涂了,说它是一个派生类,因为它继承自Object只会让事情变得更糟,这是一个非常极端的观点
using ClassLibrary1;
using System;
namespace InheritanceExample
{
class Program
{
static void Main(string[] args)
{
IEmployee emp;
emp = new Manager(1001, "Vikram", "USA");
Console.WriteLine($"Managers EmpId: {emp.EmpId}. Name: {emp.EmpName}. Location: {emp.Location}");
Console.WriteLine($"Manager's health insurance: {emp.GetHealthInsuranceAmount()}");
//emp = new SalesMan(1002,"Sukhmeet","Austrailia");
//Console.WriteLine($"SalesMan EmpId: {emp.EmpId}. Name: {emp.EmpName}. Location: {emp.Location}");
//Console.WriteLine($"SalesMan's health insurance: {emp.GetHealthInsuranceAmount()}");
}
}
}
public Manager(int empId, string empName, string Location)
: base()
{
this._empId = empId;
this._empName = empName;
this._location = Location;
}