当您想创建类似的东西时,接口是非常好的:
using System;namespace MyInterfaceExample{ public interface IMyLogInterface { //I want to have a specific method that I'll use in MyLogClass void WriteLog();} public class MyClass : IMyLogInterface { public void WriteLog() { Console.Write("MyClass was Logged"); } } public class MyOtherClass : IMyLogInterface { public void WriteLog() { Console.Write("MyOtherClass was Logged"); Console.Write("And I Logged it different, than MyClass"); } } public class MyLogClass { //I created a WriteLog method where I can pass as a parameter any object that implements IMyLogInterface. public static void WriteLog(IMyLogInterface myLogObject) { myLogObject.WriteLog(); //So I can use WriteLog here. } } public class MyMainClass { public void DoSomething() { MyClass aClass = new MyClass(); MyOtherClass otherClass = new MyOtherClass(); MyLogClass.WriteLog(aClass);//MyClass can log, and have his own implementation MyLogClass.WriteLog(otherClass); //As MyOtherClass also have his own implementation on how to log. } }}在我的示例中,我可以是一名编写人员的开发人员
MyLogClass,而其他开发人员可以创建他们的类,并且当他们想要登录时,他们可以实现接口
IMyLogInterface。就像他们问我要使用的
WriteLog()方法需要实现什么一样
MyLogClass。他们将在界面中找到答案。



