How to get OPTIONAL interface method implementation in C# like in Objective-C 2.0?
Objective-C has protocol which is the equivalence of interface in C#. Nevertheless C# enforces to implement all method like in Objective-C 1.0.
But in Objective-C 2.0, it is now possible to mark some method in protocol as optional. Does C# allow this or will it allow this in some future?
In theory enforcing is the very purpose of interface but in practice I have experienced the burden of this hard rule in complex project: you have to create many many interfaces which can become hard to manage design or refactor. So for me this evolution of Objective-C 1.0 to Objective-C 2.0 does really make sense.
As Microsoft is generally pragmatic it would be great if they开发者_如何转开发 could do this also.
The closest you can come is an explicit implementation (so the method is not part of the publicly visible API) and then go a step further and have it throw just in case someone found it and tried to use it.
void ICanDoSomething.DoSomething()
{
throw new NotSupportedException(); // optional
}
When someone instantiates an object that implements the interface, they would not see the explicit implementation unless they are referring to the object as the interface.
An example from the BCL is an array, which implements ICollection<T>
. ICollection<T>
has an Add
method that is not useful for a fixed-length array. It's an explicit implementation in the case of an array, and if you try to use it, it will throw.
int[] array = { 1, 2, 3 };
ICollection<int> collection = (ICollection<int>)array;
collection.Add(4); // throws NotSupportedException
Of course, if you can avoid some "optional" behavior, it's best to do so. Split it out into multiple interfaces, for example, so a class only implements the interface for the behavior that is actually desired.
No, this is not possible, because this would be against the nature of an interface. If you could make the implementation of a method optional, what would happen if a piece of code expects this method to work but it doesn't, as it isn't implemented? An interface is there to offer a contract of methods which are implemented and can be used, optional methods would be against that. If you are in need of doing this, you are probably violating the single responseability rule anyway.
精彩评论