【问题标题】:Getting an error when calling a method from an injected class (C#)从注入的类调用方法时出错 (C#)
【发布时间】:2017-02-28 11:57:38
【问题描述】:

我有一个接口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()

【问题讨论】:

  • 你能发布你得到的错误吗?
  • @CodexNZ 这里是错误“'IUser' 不包含'EmployeeSpecificTask' 的定义,并且找不到接受'IUser' 类型的第一个参数的扩展方法'EmployeeSpecificTask'”
  • 所以IUser接口定义只指定了GetTasks()和GetRole()方法,而你的接口实现增加了EmployeeSpecificTask()方法。
  • 是的,这是因为我希望 EmployeeSpecificTask() 方法仅在 EmployeeRole 类中是特定的。
  • 您只能从您期望的类中访问方法。你总是可以做一个演员,但最好的选择是创建一个更专业的界面,比如IEmployeeRole : IUser

标签: c# dependency-injection


【解决方案1】:

如果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.");
  }
}

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2018-09-15
    • 2012-06-04
    • 1970-01-01
    相关资源
    最近更新 更多