使用扩展方法实现枚举类型与数值类型的相互转换
简单的说,扩展方法可以为某个类型T的所有实例都扩展出N个方法,并且T可以是值类型。
为类型T扩展方法的步骤:
1. 定义一个静态类
2. 往类中添加静态方法,其第一个参数为this T anyName,后面再是实际的方法参数
为int扩展方法Add示例:
View Code
namespace ExtensionMethods
{
static class Extension
{
public static int Add(this int i, int value)
{
return i + value;
}
}
}
using ExtensionMethods;
……
int i = 1;
int total = i.Add(100);
对于数据库中的状态、类型等字段,在程序中往往会用枚举来表示,或许扩展方法可以帮助我们完成二者的相互转换——
View Code
#region 定义枚举类型
enum MoneyType
{
dollar = 0,
rmb = 1
}
enum Sex
{
male = 0,
female = 1
}
#endregion
static class Extention
{
#region 为枚举类型扩展方法:ToInt
public static int ToInt(this MoneyType t)
{
return (int)t;
}
public static int ToInt(this Sex t)
{
return (int)t;
}
#endregion
#region 为int扩展方法:To%枚举类型%
public static MoneyType ToMoneyType(this int i)
{
return (MoneyType)i;
}
public static Sex ToSex(this int i)
{
return (Sex)i;
}
#endregion
}
使用:
View Code
int sexValue = 1;
Sex s = sexValue.ToSex();
int monetTypeValue = MoneyType.dollar.ToInt();
参考:
扩展方法:http://msdn.microsoft.com/zh-cn/library/bb383977.aspx