[英]Getting an error when calling a method from an injected class (C#)
我有一個接口IUser
,它實現了void GetTasks()
和string GetRole()
然后創建了一個類。
public class EmployeeRole : IUser
{
public void GetTasks()
{
//Get task
}
public string GetRole()
{
return "Employee";
}
public void EmployeeSpecificTask()
{
Console.Write("This is an employee's specific task.");
}
}
在創建了類和接口后,我打算將該類注入到我的Profile.cs
類中。 這是代碼:
`public class Profile
{
private readonly IUser _user;
public Profile(IUser user)
{
this._user = user;
}
public void DisplayTask()
{
_user.GetTasks();
}
public string MyRole()
{
return _user.GetRole();
}
//The error goes here
public void MySpecificTask()
{
_user.EmployeeSpecificTask();
}
public void Greetings()
{
Console.WriteLine("Hello! Welcome to profile.");
}
}
用於注入的測試程序Profile profile = new Profile(new EmployeeRole());
我的問題是,為什么在調用EmployeeSpecificTask()
時出錯? 我的EmployeeRole類上有EmployeeSpecificTask()
。
如果IUser界面如下:
public interface IUser
{
void GetTasks();
void GetRole();
}
然后,僅給定IUser對象的使用方類只能訪問該接口上的方法或屬性。 如果要通過包含EmployeeSpecificTask()方法的接口類型,則需要定義另一個接口,如下所示:
public interface INewInterface : IUser
{
void EmployeeSpecificTask();
}
這將IUser接口與新接口結合在一起,以提供對IUser方法和您要訪問的新接口的消費類訪問。 然后,應將您的Profile構造函數修改為采用新的接口類型。
public class Profile
{
private readonly INewInterface _user;
public Profile(INewInterface user)
{
this._user = user;
}
public void DisplayTask()
{
_user.GetTasks();
}
public string MyRole()
{
return _user.GetRole();
}
public void MySpecificTask()
{
_user.EmployeeSpecificTask();
}
public void Greetings()
{
Console.WriteLine("Hello! Welcome to profile.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.