Force subclasses of an interface to implement ToString

后端 未结 7 2111
猫巷女王i
猫巷女王i 2020-12-28 11:19

Say I have an interface IFoo and I want all subclasses of IFoo to override Object\'s ToString method. Is this possible?

Simpl

7条回答
  •  無奈伤痛
    2020-12-28 11:56

    I know this doesn't answer your question, but since there is no way to do what you're asking for, I thought I'd share my own approach for others to see.

    I use a hybrid of Mark and Andrew's proposed solutions.

    In my application, all domain-entities derive from an abstract base-class:

    public abstract class Entity
    {
        /// 
        /// Returns a  that represents this instance.
        /// 
        public override string ToString()
        {
            return this is IHasDescription
                       ? ((IHasDescription) this).EntityDescription
                       : base.ToString();
        }
    }
    

    The interface itself only defines a simple accessor:

    public interface IHasDescription : IEntity
    {
        /// 
        /// Creates a description (in english) of the Entity.
        /// 
        string EntityDescription { get; }
    }
    

    So now there's a fall-back mechanism built in - or in other words, an Entity that implements IHasDescription must provide the EntityDescription, but any Entity can still convert to a string.

    I know this isn't radically different from the other solutions proposed here, but I like the idea of minimizing the responsibility of the base Entity type, so that implementing the description-interface remains optional, but you're forced to actually implement the description-method if you're implementing the interface.

    IMHO, interfaces that are implemented by the object base-class should not "count" as implemented - it would be nice to have a compiler option for that, but, oh well...

提交回复
热议问题