c# – 我可以使用扩展方法继承吗?
发布时间:2020-12-15 06:43:39 所属栏目:百科 来源:网络整理
导读:我有以下几点: 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(
我有以下几点:
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"); } } 这种扩展方法绝对不会显示出来;它只适用于你继承ID2Able的东西. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |