WPF学习——枚举和数字、字符串之间的相互转化

参考:https://www.cnblogs.com/wangyblzu/p/6543037.html

枚举和数字、字符串之间的相互转化

https://blog.csdn.net/ngany/article/details/108393970

既上一篇博客中写的吧RadioButton选择的星期几传送到字符串today,方法是switch枚举类型,case给字符串today赋值。但是如果可以把枚举类型直接转化成字符串代码会简洁很多。

public WeekEnum week
{
	get { return _week; }
	set
	{
		_week = value;
		this.today = this.EnumConvertToString(_week);
		this.RaisePropertyChanged("week");
	}
}

1.枚举类型转换为字符串

private string EnumConvertToString(WeekEnum day)
{
	//方法一
	//return color.ToString();

	//方法二
	return Enum.GetName(day.GetType(), day);
}

2.枚举类型转换为数字

private int EnumConvertToInt(WeekEnum day)
{
	return (int)day;
}

3.字符串转换为枚举类型

private WeekEnum StringConvertToEnum(string str)
{
	WeekEnum day = WeekEnum.Monday;
	try
	{
		day = (WeekEnum)Enum.Parse(typeof(WeekEnum), str);
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
		return day;
	}

	return day;
}

4.数字转换为枚举类型

private WeekEnum IntConvertToEnum(int i)
{
	if (Enum.IsDefined(typeof(WeekEnum), i))
	{
		return (WeekEnum)Enum.ToObject(typeof(WeekEnum), i);
	}
	return WeekEnum.Monday;

	// return (enumColor)i;
}

https://download.csdn.net/download/ngany/12807299

你可能感兴趣的:(WPF,C#,WPF)