我可以将继承与扩展方法一起使用吗? [英] Can I use inheritance with an extension method?
问题描述
我有以下内容:
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"的键
Plus other classes with similar extensions that return the key formatted as a "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?
更新.很抱歉,我没有提到这一点,但是类似CityType的类是Enums.
Update. I am sorry I did not mention this but my classes like CityType are Enums.
推荐答案
从下面的注释中, CityType
和 CityStatus
是枚举.因此,您可以执行以下操作:
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:
您可以使用通用方法和接口 ID2Able
:
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");
}
}
这样,扩展方法就不会对每种类型都显示出来;它仅适用于您从中继承 ID2Able
的事物.
This way the extension method won't show up for absolutely every type; it'll only be available for things you inherit ID2Able
from.
这篇关于我可以将继承与扩展方法一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!