Force subclasses of an interface to implement ToString

后端 未结 7 2113
猫巷女王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 12:13

    Jon & Andrew: That abstract trick is really useful; I had no idea you could end the chain by declaring it as abstract. Cheers :)

    In the past when I've required that ToString() be overriden in derived classes, I've always used a pattern like the following:

    public abstract class BaseClass
    {
        public abstract string ToStringImpl();
    
        public override string ToString()
        {
            return ToStringImpl();
        }    
    }
    

提交回复
热议问题