English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article describes the calling methods of C# interfaces in derived classes and external classes. Shared for everyone's reference, as follows:
C# interfaces are created using the interface keyword. Interfaces can include properties, methods, and other member variables. Derived classes of an interface can implement methods from the interface. A class can inherit multiple interfaces to implement methods from these interfaces, and an interface can also derive multiple classes. Methods in an interface can be directly called in the derived class.
Example of calling in derived class:
//Interface public interface IPersonalService { //Method in interface PersonalDTO QueryByUid(int uId); } //Derived class of interface public class PersonalService : IPersonalService { //Implementing interface method in derived class--Implicit implementation public PersonalDTO QueryByUid(int uId) { return _dal.QueryByUid(uId); } //Invoking interface method in derived class public void GetInfo(int userId) { //Calling method one IPersonalService p = new PersonalService(); PersonalDTO dto = p.QueryByUid(userId); //Method Two PersonalService p2 = new PersonalService(); IPersonalService p3 = (IPersonalService)p2; PersonalDTO dto = p3.QueryByUid(userId); } }
When calling a method of an interface in an external class, first reference the namespace where the interface is located, and the subsequent steps are the same as calling in the derived class of the interface.
You can also call the interface by declaring an interface type property after referencing the namespace where the interface is located in the external class, as follows.
public IPersonalService pService{get;set;} public void getInfo() { pService.getInfo(); }
Readers who are interested in more C# related content can check the special topic of this site: 'C# Data Structures and Algorithms Tutorial', 'C# Traversal Algorithm and Technique Summary', 'C# Thread Usage Technique Summary', 'C# Common Control Usage Tutorial', 'WinForm Control Usage Summary', 'C# Array Operation Technique Summary', and 'C# Object-Oriented Programming Tutorial'.
I hope the content described in this article will be helpful to everyone in designing C# programs.
Declaration: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been edited by humans, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (when sending an email, please replace # with @ to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)