Lea*_*ner 0 c# oop interface c#-3.0 c#-4.0
只是想知道如何为我的学习目的打电话.我知道在不使用IIm或IIn.Display时通过对象创建来调用它(即只使用public void Display();)但是,我不知道如何调用它.
public interface IIn
{
void Display();
}
public interface IIM : IIn
{
void Display();
}
public class temp : IIM
{
void IIM.Display()
{
Console.WriteLine("Displaying 1");
}
void IIn.Display()
{
Console.WriteLine("Displaying 2 ");
}
static void Main()
{
temp t = new temp();
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
特定
var t = new temp();
Run Code Online (Sandbox Code Playgroud)
您只需要转换t为其中一个接口...在接口类型的变量中复制它就足够了:
IIM t1 = t;
IIn t2 = t;
t1.Display(); // Displaying 1
t2.Display(); // Displaying 2
Run Code Online (Sandbox Code Playgroud)
或将其作为参数传递给方法:
static void MyShow(IIM t1, IIn t2)
{
t1.Display(); // Displaying 1
t2.Display(); // Displaying 2
}
MyShow(t, t);
Run Code Online (Sandbox Code Playgroud)
或者您可以直接投射它并使用该方法:
((IIM)t).Display(); // Displaying 1
((IIn)t).Display(); // Displaying 2
Run Code Online (Sandbox Code Playgroud)
请注意,如果您的班级中有第三种方法
public void Display()
{
Console.WriteLine("Displaying 3 ");
}
Run Code Online (Sandbox Code Playgroud)
这会叫它
t.Display(); // Displaying 3
Run Code Online (Sandbox Code Playgroud)