1 public partial class Form1 : Form
2 {
3 public Form1()
4 {
5 InitializeComponent();
6 }
7
8 private void button1_Click(object sender, EventArgs e)
9 {
10 string s = "ss";
11 dd p = (dd)Enum.Parse(typeof(dd),s);//这里将字符串s转换为枚举p了,原创:yangyang8848.cnblog.com
13 }
14 }
15
16 public enum dd
17 {
18 mm,ss
19 }
2 {
3 public Form1()
4 {
5 InitializeComponent();
6 }
7
8 private void button1_Click(object sender, EventArgs e)
9 {
10 string s = "ss";
11 dd p = (dd)Enum.Parse(typeof(dd),s);//这里将字符串s转换为枚举p了,原创:yangyang8848.cnblog.com
13 }
14 }
15
16 public enum dd
17 {
18 mm,ss
19 }
但是这里又有了一个问题,那就是每次我从数据库中读取一个枚举都要进行一次这种操作,那样太麻烦了,能不能把这种操作进行一个简单的包装呢,做成一个只要用户指定就可以返回出固定的枚举,这里就要用到泛型了。代码如下:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{//原创:yangyang8848.cnblogs.com
string s = "ss";
dd p = (dd)Enum.Parse(typeof(dd),s);
}
private void button2_Click(object sender, EventArgs e)
{
dd p = FF<dd>.GetEnum("ss");
ll t = FF<ll>.GetEnum("oo");
}
}
public class FF<T>
{
public static T GetEnum(string ss)
{
return (T)Enum.Parse(typeof(T), ss);
}
}
public enum dd
{
mm,ss
}
public enum ll
{
kk,oo
}
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{//原创:yangyang8848.cnblogs.com
string s = "ss";
dd p = (dd)Enum.Parse(typeof(dd),s);
}
private void button2_Click(object sender, EventArgs e)
{
dd p = FF<dd>.GetEnum("ss");
ll t = FF<ll>.GetEnum("oo");
}
}
public class FF<T>
{
public static T GetEnum(string ss)
{
return (T)Enum.Parse(typeof(T), ss);
}
}
public enum dd
{
mm,ss
}
public enum ll
{
kk,oo
}
看到上边代码没有??很简单吧!!只是加了一个泛型类,那么我们就可以把字符串转换为枚举更加直观的给他人调用。