本文介绍了如何在C#中调用特定的显式声明的接口方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对如何在以下代码中调用特定接口的方法(Say IA或IB或In ...)有疑问。请帮我解决如何打电话。我已经注释了代码行,我声明了接口方法public,在这种情况下它可以工作。当我明确声明时,我不知道如何调用它:(我正在学习C#....
I have a doubt on how to call the method of particular interface (Say IA or IB or In...) in the following code. Please help me on how to call. I have commented the lines of code where I declare the interface methods "public" in which case it works. I dont know how to call it when I explicitly declare :( I am learning 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();
}
}
推荐答案
要调用显式接口方法,需要使用正确类型的变量,或者直接使用ca st到该接口:
To call an explicit interface method, you need to use a variable of the proper type, or directly cast to that interface:
static void Main()
{
Model m = new Model();
// Set to IA
IA asIA = m;
asIA.Display();
// Or use cast inline
((IB)m).Display();
Console.ReadLine();
}
这篇关于如何在C#中调用特定的显式声明的接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!