什么是“?"做? [英] what does '?' do?

查看:78
本文介绍了什么是“?"做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我是c#初学者,不知道这段代码是什么?"及其结构:

Hi,
I''m a c# beginner and I don''t know what''s ''?'' and its structure in this code:

public bool IsLeapYear(int year)
{
    return year % 4 == 0 ? true : false;
}

推荐答案

这是一个运算符,其含义与以下内容相同:
This is an operator and means the same as:
public bool IsLeapYear(int year)
{
    if (year % 4 == 0)
        return true;
    else
        return false;
}


或者更简单:


or, simpler:

public bool IsLeapYear(int year)
{
    return year % 4 == 0;
}


尽管如此,我还是建议您使用:


Nonetheless I would recommend you to use:

System.DateTime.IsLeapYear(year);


因为您的代码在正确的Le年中不完整.以下是完整的代码:


because your code is incomplete for correct Leap Year. Below is the complete code:

public bool IsLeapYear(int year)
{
    if (year % 400 == 0)
        return true;
    else if (year % 100 == 0)
        return false;
    else if (year % 4 == 0)
        return true;
    else
        return false;
}


或者更简单:


or, simpler:

public bool IsLeapYear(int year)
{
    if (year % 400 == 0)
        return true;
    if (year % 100 == 0)
        return false;
    if (year % 4 == 0)
        return true;
    return false;
}




?被称为条件运算符.有关您可以在msdn上找到的更多信息:
http://msdn.microsoft.com/en-us/library/ty67wk28(VS .80).aspx [ ^ ]



http://msdn.microsoft.com/en-us/library/6a71f45d [ ^ ]

问候
Robert
Hi,

? is called conditional operator. more about that you can find on msdn:
http://msdn.microsoft.com/en-us/library/ty67wk28(VS.80).aspx[^]

and

http://msdn.microsoft.com/en-us/library/6a71f45d[^]

Regards
Robert


这与C语言中的三元运算符相同
它只是执行?运算符左侧的条件表达式.如果结果满足(等于true),则在?运算符之后立即执行表达式,否则在:运算符
之后执行表达式
如果假设年份为1996

Hi this is same as ternary operator in C
It just executes the Conditional expression to the left of the ? operator. If the result satisfies (means true) it execute the expression immediate next to ? operator, otherwise it execute the expression after the : operator

if suppose year is 1996

return 1996%4==0 ? true : False



在这种情况下,编译器首先执行?运算符
左侧的条件 然后



in this the compiler first execute the conditions to the left of ? operator
then

return 0==0 ? true : False


条件为true,因此它立即在?旁边开始执行语句,在此返回true,否则在本示例中,year = 1998计算的值不等于零.它忽略紧靠?运算符的语句,并在之后执行语句:运算符为False
因此返回false

假设a = 10 b = 15


condition true so it start execute statement immediately next to ? here its return true, otherwise in this example say year =1998 the calculated value is not equal to zero It ignores the Statement immediately next to ? operator and execute the statement after the : operator which is False
hence it returns false

lets say a=10 b=15

public int void operate()
{
 c=(a>b)? a-b:a+b;
}


一样

this is same like

if (a>b)
c=a-b;
else 
c=a+b;


对于该条件,c = 25,因为(a> b)为假.您可以将其用于简单的条件检查.


for this condition c=25 because (a>b) is false. you can use this for simple conditional checking.


这篇关于什么是“?"做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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