检查字符串是否可以转换为其他类型(C#)
我正在用C#做一些测试,现在我需要知道一些东西。我创建了一个类,如下所示:检查字符串是否可以转换为其他类型(C#),c#,types,enums,C#,Types,Enums,我正在用C#做一些测试,现在我需要知道一些东西。我创建了一个类,如下所示: class DChanger { //Just ignore this: private string section = Csuc.CPanel.CPanelSection.Appearance; //Then the constructor: DChanger dchange = new DChanger(Internet); public void DChanger(string s
class DChanger
{
//Just ignore this:
private string section = Csuc.CPanel.CPanelSection.Appearance;
//Then the constructor: DChanger dchange = new DChanger(Internet);
public void DChanger(string subsection)
{
//Code
}
}
所以,现在。我想检查“subsection”是否可以转换为其他类型。例如,我有一个枚举:
enum Subsections { Internet, Programming };
我想检查“subsection”是“Internet”还是“Programming”(在本例中,因为真正的enum有更多的部分)。
我可以这样做吗?谢谢 您可以使用Enum.Parse并监视ArgumentException类型的异常。 也可以使用Enum.TryParse
更多信息请参见此处要快速测试,最好使用Enum类it进行测试:
public void DChanger(string subsection)
{
bool b = Enum.GetNames(typeof(Subsections)).Contains(subsection);
}
在文本和代码缩进之间添加一行新行,使其格式正确:)哦,对不起。你保存了我的格式!您能使用TryParse()吗?您是专门询问枚举吗?其他类型呢?或者您只是在谈论将字符串与字符串枚举中的字符串进行比较?。。。而且更喜欢。如果可以的话,不要使用异常来控制流。