我有以下几点:
- 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");
- }
加上类似扩展名的其他类,返回格式化为“D2”的密钥
有没有办法可以从基类继承,并让基类提供这样的功能
我不需要重复相同的扩展方法代码?
更新.对不起,我没有提到这个,但我的类CityType是枚举.
解决方法
从以下评论中,CityType和CityStatus是枚举.所以你可以这样做:
- public static class Extensions
- {
- public static string D2(this Enum key)
- {
- return Convert.ToInt32(key).ToString("D2");
- }
- }
原来的答案:
您可以使用通用方法和接口ID2Able:
- public static class Extensions
- {
- public static string D2<T>(this T key) where T : ID2Able
- {
- return ((int) key).ToString("D2");
- }
- }