I’ve implemented ISerializable in both a child class and a parent class, like this:
class CircuitElement : ISerializable
{
...
protected void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("ID", ID);
}
}
class Bus : CircuitElement, ISerializable
{
...
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
((ISerializable)base).GetObjectData(info,context);
info.AddValue("Voltage", Voltage);
info.AddValue("BaseVoltage", BaseVoltage);
info.AddValue("Location", Location);
}
}
But in the child class Bus, I’m getting the error Use of keyword base is not valid in this context. I know I can just implement the interface implicitly on the parent CircuitElement class, and then I don’t have to worry about the conversion, but was under the impression that explicit implementation is more appropriate for this scenario (for reasons akin to those presented here: https://stackoverflow.com/a/143425/996592)
Is there a way to do the conversion, or am I stuck implementing the ISerializable interface in the parent class implicitly?
Personally, I disagree with the perspective presented in the answer you linked to. Explicit interface implementation is simply more problematic, for exactly the reason you’ve given: it really doesn’t play nicely with inheritance.
If you’re reimplementing an interface which has been implemented explicitly, there’s just no way of calling that implementation on an object of a type which reimplements the same interface, including from within the code of that reimplementation.
Two options:
Use implicit interface implementation instead. Personally I usually find this simpler. I only use explicit interface implementation when the interface has members which don’t really make sense when you’re thinking about the class itself.
Continue to use explicit interface implementation, but make that implementation just call a protected virtual method. You can then override that virtual method in the derived class and call the base implementation.