我试图检查枚举成员的用户价值,但它总是给予其他部分。 [英] I am trying to check user value against enum member but it is always giving else part .

查看:105
本文介绍了我试图检查枚举成员的用户价值,但它总是给予其他部分。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;

public class GetValuesTest
{
    enum Colors { Red, Green, Blue, Yellow };
    
    public static void Main()
    {
        Colors myColor = Colors.Red;
        Console.WriteLine(" Enter String");
        string s = Console.ReadLine();
        if (myColor.Equals(s))
           Console.WriteLine("ok");
        else
           Console.WriteLine("not ok");
        
    }
}



我的输入是红色仍然给予其他部分。迫切需要帮助。谢谢


my input is Red still giving else part. urgently need help . thank you

推荐答案

enum Colors { Red, Green, Blue, Yellow };
static void Main(string[] args)
{
   Colors myColor = Colors.Red;
   Console.WriteLine(" Enter String");
   string s = Console.ReadLine();
   if (myColor.ToString().Equals(s))
      Console.WriteLine("ok");
   else
      Console.WriteLine("not ok");
}





添加代码块,缩进修正



code block added, indentation corrected


你可以使用Enum.IsDefined(Type,string)检查你是否有一个有效的枚举值。



更好的方法是在NameSpace范围内使用Enum.TryParse(string,out EnumType):
You can use Enum.IsDefined(Type, string) to check if you have a valid Enum Value.

A much better way is to use Enum.TryParse(string, out EnumType):
// in NameSpace scope, or Class scope
enum Colors { Red, Green, Blue, Yellow };

// in a method or EventHandler ...
string s = "Red";

if (Enum.IsDefined(typeof(Colors), s))
{
   // yes, this is a valid name for a Colors Value
}
else
{
   // throw error, or whatever
}

Colors colorResult;

if(Enum.TryParse(s, out colorResult))
{
    // valid Colors now in colorResult
}
else
{
    // throw error, or whatever
}

这两种方法都区分大小写!如果可能的用户错误案例输入是您关心的事情,您可以执行以下操作:



1.将所有Enum条目设为大写或小写。



2.将用户输入转换为大写或小写,以便在比较之前匹配Enum条目的情况。

Both these methods are case-sensitive ! If possible user wrong-case entry is something you are concerned about, you can do something like:

1. make all your Enum entries upper- or lower-case.

2. convert the user-input to upper- or lower-case to match the case of Enum entries before comparison.


这篇关于我试图检查枚举成员的用户价值,但它总是给予其他部分。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆