Is it allowed for a class to implement an interface plus additional private method(s) in C#?
I have the following interface:
interface IExcelServices
{
Dictionary<string, string[]> FilterFields(Dictionary<string, string[]> excelContent);
Dictionary<string, string[]> ParseExcelFile(string path);
}
Which is implemented by the following class:
public class ExcelServices : IExcelServices
{
p开发者_如何学Cublic Dictionary<string, string[]> FilterFields(Dictionary<string,
string[]> excelContent)
{
//somecode
}
public Dictionary<string, string[]> ParseExcelFile(string path)
{
//somecode
}
private void ReleaseObject(object obj)
{
//somecode
}
}
My code compiles without any problem but I was wondering whether adding a private method (or in general any method) which is not in the interface definition is a good OO programming practice or not.
Of course it is OK to add other members in a class that implements an interface. An interface is just a contract that specifies what the class must implement, but it can also add any members it needs (actually most classes have more members that the ones declared in the interface)
The idea behind an interface is that the classes implementing it must include the functionality of the interface. This doesn't mean they have to be limited to what is in the interface, you can extend on it as much as you like, it's perfectly reasonable to have methods that aren't part of the interface. Likewise, you could implement more than one interface.
Yes, that's fine - but your methods implementing the interface either have to be public or have to implement the method explicitly, e.g.
public Dictionary<string, string[]> FilterFields(...)
or
Dictionary<string, string[]> IExcelServices.FilterFields
Your current code will fail to compile, as the default visibility for methods is private
.
It's the default for me: implementing some inferface makes sure others can use your class in a simple way and that your object (class) can be taken as single parts (interfaces).
But to work a class could need extra operations that you implement with private methods.
Be careful: methods implementing interfaces methods MUST BE public!!
Good OO Programming practice would not inhibit implementing beyond an interface. Infact, the purpose of an interface is to be complimentary to the rest of a classes implementation.
EDIT
Furthermore, it is impossible for a non abstract class to be limited to just an interface and be useable. Interfaces do not define contructors which a creatable class must have.
Yes, this is possible. All the methods in the interface are required to be implemented though.
精彩评论