简体   繁体   English

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

[英]Getting an error when calling a method from an injected class (C#)

I have an interface IUser which implements void GetTasks() and string GetRole() then i create a class. 我有一个接口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.");
    }
}

after creating classes and interface im planning to inject that class on my Profile.cs class. 在创建了类和接口后,我打算将该类注入到我的Profile.cs类中。 Here is the code: 这是代码:

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

The test program for injection Profile profile = new Profile(new EmployeeRole()); 用于注入的测试程序Profile profile = new Profile(new EmployeeRole());

My question is why I'm getting error when calling EmployeeSpecificTask() ? 我的问题是,为什么在调用EmployeeSpecificTask()时出错? I have EmployeeSpecificTask() on my EmployeeRole class. 我的EmployeeRole类上有EmployeeSpecificTask()

If IUser interface is as below: 如果IUser界面如下:

public interface IUser
{
void GetTasks();
void GetRole();
}

Then a consuming class that is only given an IUser object can only access the methods or properties on that interface. 然后,仅给定IUser对象的使用方类只能访问该接口上的方法或属性。 If you want to pass through an interface type that includes the EmployeeSpecificTask() method, you will need to define another interface like below: 如果要通过包含EmployeeSpecificTask()方法的接口类型,则需要定义另一个接口,如下所示:

public interface INewInterface : IUser 
{ 
  void EmployeeSpecificTask(); 
}

This combines the IUser interface with the new one to give a consuming class access to both the IUser methods and the new one you are wanting access to. 这将IUser接口与新接口结合在一起,以提供对IUser方法和您要访问的新接口的消费类访问。 Then your Profile constructor should be modified to take the new interface type instead. 然后,应将您的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