public interface IDataBase
{
void Execute();
}
public class SqlDataBase : IDataBase
{
public void Execute()
{
Console.WriteLine("Executing SQL");
}
public void SqlSpecificMethod() // not part of the interface, so only available to classes that implement it directly (not via a base class)
{
}
}
public class OracleDataBase : IDataBase // implementing the interface directly, so we can call Execute and any other Oracle specific methods.
{ // if we were to inherit from a base class that implemented the interface, then we would not be able to call Oracle specific methods.
public void Execute() // this is because when you inherit from a base class, you are inheriting all of its members (including those in interfaces it implements).
// this means that any members defined in derived classes will not be accessible through an instance of the base type.
Console.WriteLine("Executing Oracle"); // for example if we had an instance of DataBase and called Execute on it, then even though our actual type was OracleDataBase, only the implementation in DataBase would be called as that is what is exposed by the interface.
// this is why when implementing an interface it's often better to implement it directly rather than inheriting from a base class which implements it - as you won't have access to any members defined in derived classes through an instance of the base type (as they are not exposed by the interface).
public void OracleSpecificMethod() // available only to classes that implement IDataBase directly - i.e. those deriving from DataBase will not have access to this method as they do not implement IDataBase themselves (only their parent does). This is because when you inherit from a base class, all members of that parent become part of your own type - including those declared in interfaces implemented by the parent. Therefore any members declared in derived classes are not accessible through an instance of just the parent type as they are not exposed by any interfaces implemented by it.
创作工场
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!