I have the following:
public static class CityStatusExt
{
public static string D2(this CityStatus key)
{
return ((int) key).ToString(\"D2\");
-
You can make the method generic. C# will infer the type:
public static class Extension
{
public static string D2<T> (this T key)
{
return ((int)(object) key).ToString("D2");
}
}
讨论(0)
-
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<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.
讨论(0)
-
Your enums already all inherit from a common base class, namely 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):
public static class EnumExtensions
{
public static string D2(this Enum e)
{
return e.ToString("D").PadLeft(2, '0');
}
}
讨论(0)
- 热议问题