c# - 我如何编写介于两个值之间的 if 语句?

这是我的代码,对于我的 if 语句,我希望它位于两个值之间,例如:

if(rating < 5 > 2);

所以我是说我希望它只在该值低于 5 但高于 2 时打印命令。 有没有办法做到这一点?感谢您的宝贵时间。

这是我的代码。

 public static void Main(string[] args)
    {
        Console.WriteLine("What would you rate starcraft out of 10?");
        int rating = Console.Read();


        if (rating < 5) ;
        {
            Console.WriteLine("Not good enough!");
            Console.ReadLine();
        }

        if (rating > 5) ;
        {
            Console.WriteLine("OOOOOOOOO yeeeeeeee");
            Console.ReadLine();

        }
        if (rating > 8) ;
        {
            Console.WriteLine("We are bestfriends now ;)");
            Console.ReadLine();

最佳答案

使用conditional logical AND operator && :

if (rating < 5 && rating > 2)
{
}

或pattern matching ( read more #1 , read more #2 ):

if (rating is < 5 and > 2)
{    
}

附言

您可以使用 switch expression 进行一些重构并命令检查以删除一些代码重复并提高可读性(请注意,与以下相比,原始代码不涵盖 rating == 5 情况):

var rating = ...;
var message = rating switch
{
    < 2 => "Terrible",
    < 5 => "Not good enough!",
    < 8 => "OOOOOOOOO yeeeeeeee",
    _ => "We are bestfriends now ;)"
};

Console.WriteLine(message);
Console.ReadLine();

https://stackoverflow.com/questions/74889190/

相关文章:

java - 为什么 LocalDateTime.ofInstant() 需要 ZoneId

coldfusion - 在 Coldfusion/CFML 中,如何将长十进制数格式化为标准的两位

oop - 理解对象交互的一些技巧是什么

php - 如何在 PHP 中将数字转换为字母?

php - 静默捕获php "file_get_contents"错误

php - 过滤消息的内容上的单词黑名单

amazon-ec2 - 一个 Amazon EC2 实例可以服务多少用户?

.net - Session.Timeout 和 Server.ScriptTimeout 有什么区

regex - perl中用-e和正则表达式匹配的文件名

unit-testing - TDD 如何处理异常和参数验证?