c# - Define optional implementation methods in Interface? -
Is it possible to define an interface with optional implementation methods? For example, I have the following interface definition in the form of the IDTider in my Core Library:
Public Interface IDataReader & lt; T & gt; {Zero Start Reid (T Data); Zero stop (); }
However, in my current implementation, the stop () method has never been used or implemented in all my implementation sections, this method can not be applied, as That is to throw NotImplementedExcetion as the default:
class MyDataReader: IDataReader & lt; MyData & gt; {... public void Stop () {// This does not appear to be an implementation of an incomplete code throwing notepointed exception (); }
Of course, I can remove the throw exception code and leave it blank.
When I created this Data Reader Interface, I thought that it might stop the process of reading that we will use the stop () sometime later in the future.
Still, it is not possible to alternatively prevent this method? I think the only way is to define either the two interfaces with a stop and no other like IDataReader and IDataReader2. Another option is to break it into the interface like this:
Interface idta reader & lt; T & gt; {Zero Start Reid (T Data); } Interface istop {zero stop (); }
In my implementation cases, I will have to use it as an ISP to check whether my implementation supports () method:
reader.StartRead my information); .... / Where is it when I have to stop the reader ISOP stoppable = reader as ISOP; If (stoppage! = Null) stoppable. Stop (); ...
Still I have to write those code any suggestions? Not sure if there is any way to define alternate implementation methods in .in or C # in any interface?
For information, another approach to BCL is quite similar, support on the same interface Does *
, that means
bool SupportsStop {get;} stop zero ();
(Examples, for example, in IBindingList
).
I'm not showing that this is "pure" or anything, but it works - but that means that now you have two methods, not one
for information, if the implementation is common between all implementation, then you can use extensions; For a trivial example:
Public static Zero AddRange & lt; T & gt; (This is the IList & lt; T & gt; List, IEnumerable & lt; T & gt; Items) {foreach item item in item T}. ; }
(or equivalent to your interface). If you provide a more specific version against the concrete type, it takes precedence (but only if the collar variable as concrete type does not know the interface). Therefore, with the above mentioned, any intentional list & lt; T & gt;
uses list
version of ; But if it has a list & lt; T & gt;
but only about IList & lt; T & gt; As the address
, this extension will use the method.
Comments
Post a Comment