Can I use inheritance with an extension method?

后端 未结 3 1647
猫巷女王i
猫巷女王i 2021-01-17 19:10

I have the following:

public static class CityStatusExt
{
    public static string D2(this CityStatus key)
    {
        return ((int) key).ToString(\"D2\");         


        
相关标签:
3条回答
  • 2021-01-17 19:23

    You can make the method generic. C# will infer the type:

    public static class Extension 
    { 
        public static string D2<T> (this T key) 
        { 
            return ((int)(object) key).ToString("D2"); 
        } 
    }
    
    0 讨论(0)
  • 2021-01-17 19:27

    From the comment below, CityType and CityStatus are enums. Therefore you can do this:

    public static class Extensions
    {
        public static string D2(this Enum key)
        {
            return Convert.ToInt32(key).ToString("D2");
        }
    }
    

    Original answer:

    You can use a generic method and an interface ID2Able:

    public static class Extensions
    { 
        public static string D2<T>(this T key) where T : ID2Able
        { 
            return ((int) key).ToString("D2"); 
        } 
    }
    

    This way the extension method won't show up for absolutely every type; it'll only be available for things you inherit ID2Able from.

    0 讨论(0)
  • 2021-01-17 19:48

    Your enums already all inherit from a common base class, namely System.Enum. So you can do this (Enums don't accept "D2" as a format string, but they accept "D", so I added a call to PadLeft):

    public static class EnumExtensions
    {
        public static string D2(this Enum e)
        {
            return e.ToString("D").PadLeft(2, '0');
        }
    }
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题