如何解决为什么我们可以从派生类的构造函数-C#中调用接口.ctor [base]
以下是代码:
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";
}
}
}
在这里,类Manager
实现了接口IEmployee
。接口应该没有构造函数。
那么,Manager constructor
怎么可能调用IEmployee constructor
?
以下是IEmployee interface
:
namespace ClassLibrary1
{
public interface IEmployee
{
string GetHealthInsuranceAmount();
int EmpId
{
get; set;
}
string EmpName { get; set; }
string Location
{
get; set;
}
}
}
这是调用程序:
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 class constructor
调用IEmployee interface constructor
的方式:
public Manager(int empId,string Location)
: base()
{
this._empId = empId;
this._empName = empName;
this._location = Location;
}
请参阅:我正在使用C#语言版本7.3(.Net Framework 4.8)-但这无关紧要。
解决方法
C#中的每个类都源自Object
基类。
C#为类继承和接口实现使用相同的关键字:
,这一事实可能使您感到困惑。
调用: base()
时,没有调用接口的构造函数。它没有一个。您正在调用System.object
的构造函数,它是一个没有参数的简单构造函数。
尝试删除该接口,然后查看它是否仍然有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。