Examples of C Interface Calling Methods in Derived and External Classes

  • 2021-12-05 07:07:40
  • OfStack

This article illustrates how the C # interface calls methods in derived and external classes. Share it for your reference, as follows:

The interface of C # is created through the interface keyword, and can contain member variables such as properties and methods in the interface. Interface can implement methods in the interface. A class can inherit multiple interfaces to implement methods in these interfaces, and an interface can also derive multiple classes. Methods in interfaces can be implemented by one or more of these classes. Methods in the interface can be called directly in the derived class of the interface.

Invoke an example in a derived class:


// Interface 
public interface IPersonalService
{
   // Methods in the interface 
   PersonalDTO QueryByUid(int uId);
}
// Interface derived class 
public class PersonalService : IPersonalService
{
    // Implementing interface methods in derived classes -- Implicit implementation 
    public PersonalDTO QueryByUid(int uId)
    {
      return _dal.QueryByUid(uId);
    }
    // Invoking interface methods in derived classes 
    public void GetInfo(int userId)
    {
      // Calling mode 1
      IPersonalService p = new PersonalService();
      PersonalDTO dto = p.QueryByUid(userId);
      // Calling mode 2
      PersonalService p2 = new PersonalService();
      IPersonalService p3 = (IPersonalService)p2;
      PersonalDTO dto = p3.QueryByUid(userId);
    }
}

Calling a method of an interface in an external class refers to the namespace of the interface first and then the steps are the same as calling it in a derived class of the interface.

An interface can also be invoked by declaring an attribute of an interface type after referencing the namespace in the external class, as follows.


public IPersonalService pService{get;set;}
public void getInfo()
{
    pService.getInfo();
}

For more readers interested in C # related content, please check the topics on this site: "C # Data Structure and Algorithm Tutorial", "C # Traversal Algorithms and Skills Summary", "C # Thread Use Skills Summary", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"

I hope this article is helpful to everyone's C # programming.


Related articles: