using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MethodInterface { class CA { public string Name; public int Age; } class CB { public string First; public int Last; } class Program { static void PrintInfo(CA fg) { Console.WriteLine("Name:{0},Age{1}", fg.Name, fg.Age); Console.ReadKey(); } static void Main() { //没有接口,这里的函数只能是CA,如果加入接口可以实现CA、CB互换。 CA a = new CA(); PrintInfo(a); } } /// <summary> /// 声明一个接口,包含两个方法,这两个方法都返回string /// 接口需要被实现,实现后才能用 /// </summary> interface Iinfo { string GetName(); string GetAge(); } class CA1 : Iinfo { public string Name; public int Age; //实现接口 public string GetName() { return Name; } public string GetAge() { return Age.ToString();} } class CB1 : Iinfo { public string First; public string Last; public double Personal; //实现接口 public string GetName() { return First + "" + Last; } public string GetAge() { return Personal.ToString(); } } class Program1 { //使用接口 static void PrintInfo1(Iinfo Iin) { Console.WriteLine("Name:{0},Age{1}", Iin.GetName(), Iin.GetAge()); } static void Main() { CA1 a = new CA1() { Name = "john doe",Age=35 }; CB1 b = new CB1() { First ="jane",Last ="doe",Personal=33}; //对象的引用能自动转换为他们实现接口的引用,自动找到 PrintInfo1(a); PrintInfo1(b); } } }
原文:https://www.cnblogs.com/JazzYan/p/11051700.html