C#中的接口
interface
[public|protected|private] interface InterfaceName
{
//mothed
// propery
// event
//delegate
}
在實現接口時,帶接口名與不帶接口的區別
不帶的區別eg:
public interface IMyShow
{
void Show();
}
public class MyShow:IMyShow
{
public void Show()//必須寫上前的public若寫成void Show()出錯
{
System.Console.Write(" 不帶接口名");
}
}
public class MyMain
{
public static void Main()
{
// 用類定義引用
MyShow obj=new MyShow();
obj.Show();
//用接口引用方法
IMyShow obj2=new MyShow();
obj2.Show();
}
}
//帶接口名
public interface IMyShow
{
System.Console.Write("帶接口名");
}
public class MyShow:IMyShow
{
void IMyShow.Show()// 前面不能帶上任何限定詞
{
System.Console.Write("帶接口名");
}
}
public class MyMain
{
public static void Main()
{
MyShow obj=new MyShow();
obj.Show();//非法因為加了限定詞後,這個方法專屬於專們的一個引用,只能有接口去引用
IMyShow obj2=new MyShow();
obj2.Show();
}
}
看完上面的內容我想為C#的愛好留個問題。請大家一起來討論一下
public interface IMyShow
{
void Show();
}
public interface IMyShow2
{
void Show();
}
public class Myclass:IMyShow,IMyShow2
{
public Myclass()
{
}
void IMyShow.Show()
{
System.Console.Write("IMyShow");
}
public void Show()
{
System.Console.Write("Myclass show");
}
void IMyShow2.Show()
{
System.Console.Write("IMyShow2.Show()");
// TODO: 添加 Myclass.Show 實現
}
}
class Class1
{
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
IMyShow obj2=new Myclass ();
obj2.Show();
IMyShow obj1=new Myclass();
obj1.Show();
Myclass obj=new Myclass();
obj.Show();
}
}
}
Namespace wfgSpace
Public Interface IMyShow
Sub Show()
Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
End Interface
Public Interface IMyShow2
Sub Show()
Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
End Interface
Public Class MyCls : Implements IMyShow, IMyShow2
Private iValue As Integer
Sub Show() Implements IMyShow.Show
System.Console.Write("wfng fu guo")
End Sub
Sub Show2() Implements IMyShow2.Show
System.Console.Write("wfg")
End Sub
Function Add2(ByVal a As Integer, ByVal b As Integer) As Integer Implements IMyShow.Add, IMyShow2.Add
iValue = a + b
System.Console.WriteLine("{0}+{1}={2}", a, b, iValue)
End Function
End Class
Public Class Common
Public Shared Sub main()
Dim obj As MyCls = New MyCls
Dim obj2 As IMyShow = New MyCls
Dim obj3 As IMyShow2 = New MyCls
System.Console.WriteLine("Class MyCls Object")
obj.Show2()
obj.Add2(5, 4)
System.Console.WriteLine("interface IMyShow object")
obj2.Show()
obj2.Add(5, 4)
System.Console.WriteLine("interface IMyShow2 object")
obj3.Show()
obj3.Add(5, 4)
End Sub
End Class
End Namespace