如何在C#中调用特定的显式声明的接口方法
我对如何在以下代码中调用特定接口的方法(Say IA或IB或In …)有疑问。 请帮我解决如何打电话。 我已经注释了代码行,我声明了接口方法“public”,在这种情况下它可以工作。 当我明确宣布时,我不知道如何调用它:(我正在学习C#….
interface IA { void Display(); } interface IB { void Display(); } class Model : IA, IB { void IA.Display() { Console.WriteLine("I am from A"); } void IB.Display() { Console.WriteLine("I am from B"); } //public void Display() //{ // Console.WriteLine("I am from the class method"); //} static void Main() { Model m = new Model(); //m.Display(); Console.ReadLine(); } }
要调用显式接口方法,您需要使用正确类型的变量,或直接转换为该接口:
static void Main() { Model m = new Model(); // Set to IA IA asIA = m; asIA.Display(); // Or use cast inline ((IB)m).Display(); Console.ReadLine(); }
将被调用的方法取决于调用它的类型。 例如:
请注意,为了清楚起见,我创建了两个项目。 但实际上,你不想这样做,你应该只在类型之间转换对象。
static void Main(string[] args) { // easy to understand version: IA a = new Model(); IB b = new Model(); a.Display(); b.Display(); // better practice version: Model model = new Model(); (IA)model.Display(); (IB)model.Display(); } interface IA { void Display(); } interface IB { void Display(); } class Model : IA, IB { void IA.Display() { Debug.WriteLine("I am from A"); } void IB.Display() { Debug.WriteLine("I am from B"); } }
输出:
I am from A I am from B
为了调用显式接口方法,您必须保持对该接口类型的引用或者对其进行强制转换:
IB ib = new Model(); ib.Display(); IA ia = (IA)ib; ia.Display();
您需要为此过程使用显式接口实现 。
但是,如果两个接口成员不执行相同的function,则可能导致一个或两个接口的错误实现。 可以实现接口成员显式创建仅通过接口调用的类成员,并且特定于该接口。 这是通过使用接口名称和句点命名类成员来完成的。
interface IA { void Display(); } interface IB { void Display(); } public class Program:IA,IB { void IA.Display() { Console.WriteLine("I am from A"); } void IB.Display() { Console.WriteLine("I am from B"); } public static void Main(string[] args) { IA p1 = new Program(); p1.Display(); IB p2 = new Program(); p2.Display(); } }
输出将是:
I am from A I am from B
这是一个DEMO 。