简体   繁体   English

我可以使用扩展方法继承吗?

[英]Can I use inheritance with an extension method?

I have the following: 我有以下内容:

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


public static class CityTypeExt
{
    public static string D2(this CityType key)
    {
        return ((int) key).ToString("D2");
    }

Plus other classes with similar extensions that return the key formatted as a "D2" 加上具有类似扩展名的其他类,返回格式为“D2”的键

Is there a way I could inherit from a base class and have the base class provide the functionality so don't I don't have to repeat the same extension method code? 有没有一种方法可以从基类继承并让基类提供功能所以我不必重复相同的扩展方法代码?

Update. 更新。 I am sorry I did not mention this but my classes like CityType are Enums. 对不起,我没有提到这个,但像CityType这样的课程是Enums。

You can make the method generic. 您可以使方法通用。 C# will infer the type: C#将推断出类型:

public static class Extension 
{ 
    public static string D2<T> (this T key) 
    { 
        return ((int)(object) key).ToString("D2"); 
    } 
}

From the comment below, CityType and CityStatus are enums. 从下面的评论中, CityTypeCityStatus是枚举。 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 : 您可以使用通用方法和接口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. 它只适用于你继承ID2Able东西。

Your enums already all inherit from a common base class, namely System.Enum . 您的枚举已经全部继承自公共基类,即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): 所以你可以这样做(Enums不接受“D2”作为格式字符串,但是他们接受“D”,所以我添加了对PadLeft的调用):

public static class EnumExtensions
{
    public static string D2(this Enum e)
    {
        return e.ToString("D").PadLeft(2, '0');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM