Can I use inheritance with an extension method?

后端 未结 3 1672
猫巷女王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: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(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.

提交回复
热议问题