繁体   English   中英

从注入的类(C#)调用方法时发生错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM