public void InterfaceExecTest() { Console.WriteLine("InterfaceExecTest"); Stopwatch stopwatch = new(); IMyInterface iMyClass = new MyClass(); iMyClass.MyFunc(); stopwatch.Restart(); for (int i = 0; i < 1_000_000_000; i++) { iMyClass.MyFunc(); } stopwatch.Stop(); Console.WriteLine($"interface child excute: {stopwatch.ElapsedMilliseconds}"); MyClass myClass = new(); IMyInterface convertMyClass = myClass; convertMyClass.MyFunc(); stopwatch.Restart(); for (int i = 0; i < 1_000_000_000; i++) { convertMyClass.MyFunc(); } stopwatch.Stop(); Console.WriteLine($"convert child excute: {stopwatch.ElapsedMilliseconds}"); //没有差别 //InterfaceExecTest //interface child excute: 288 //convert child excute: 291 }
static void Main(string[] args) { Product product = new Product("123", "213"); Furniture tech = new Furniture("456", "789", "456789"); closet closet1 = new closet(); IMyInterface myInterface = closet1; IAnotherInterface[] arr = new IAnotherInterface[3]; arr[0] = product; arr[1] = tech; arr[2] = closet1; Console.WriteLine(product.ToString()); Console.WriteLine(tech.ToString()); Console.WriteLine(closet1.MyFunc()); Console.WriteLine(myInterface.MyFunc()); Console.WriteLine($"myInterface is IMyInterface = {myInterface is IMyInterface}"); Console.WriteLine($"myInterface is Tabet = {myInterface is closet}"); foreach (IAnotherInterface x in arr) { Print.IAmPrinting(x); } }
static void Main(string[] args) { Product product = new Product("123", "213"); Sweets tech = new Sweets("456", "789", "456789"); Flower tablet = new Flower(); IMyInterface myInterface = tablet; IAnotherInterface[] arr = new IAnotherInterface[3]; arr[0] = product; arr[1] = tech; arr[2] = tablet; Console.WriteLine(product.ToString()); Console.WriteLine(tech.ToString()); Console.WriteLine(tablet.MyFunc()); Console.WriteLine(myInterface.MyFunc()); Console.WriteLine($"myInterface is IMyInterface = {myInterface is IMyInterface}"); Console.WriteLine($"myInterface is Tabet = {myInterface is Flower}"); foreach (IAnotherInterface x in arr) { Print.IAmPrinting(x); } }