Force subclasses of an interface to implement ToString

后端 未结 7 2061
猫巷女王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:14

    Sorry to bury out this old thread from the grave, specially as our dear @jon-skeet already provided his own answer.

    But if you want to keep the interface and not use an abstract class, I guess this is still possible by simply having your interface implementing the System.IFormattable interface.

    interface IFoo : IFormattable
    {
    }
    

    The only thing to keep in mind is, to properly implement this IFormattable, the concrete implementation should overwrite the Object.ToString() as well.

    This is clearly explained in this nice post.

    Your concrete class is now like

    public class Bar : IFoo
    {
        public string ToString(string format, IFormatProvider formatProvider)
        {
            return $"{nameof(Bar)}";
        }
    
        public override string ToString()
        {
            return ToString(null, System.Globalization.CultureInfo.CurrentCulture);
        }
    }
    

    Hope this might still help anyone.

    0 讨论(0)
提交回复
热议问题