简体   繁体   中英

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.

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. 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());

My question is why I'm getting error when calling EmployeeSpecificTask() ? I have EmployeeSpecificTask() on my EmployeeRole class.

If IUser interface is as below:

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. If you want to pass through an interface type that includes the EmployeeSpecificTask() method, you will need to define another interface like below:

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. Then your Profile constructor should be modified to take the new interface type instead.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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