C # operator?? And?:

Source: Internet
Author: User

C # operator?? And?:

Let's look at the following code:

string strParam = Request.Params["param"];if ( strParam== null ){    strParam= "";} string strParam=  Request.Params["param"] == null ? "": Request.Params["param"];

你发现,尽管实现的同一个功能,但第二段代码要比第一段代码是不是更简洁。这里的” ?:“就是一个三元的操作符。利用这个三元操作符也称条件操作符,就很简单的把一个if语句给实现了。在使用条件操作符的时候要注意,假定条件表达式是这样 x?y:z,表达式类型的只能是使y 和z的变量类型之一,换句话说就是 y和z的变量类型决定这个条件表达式的类型,无论y和z是同一类型,还是y和z不是同一类型。 如果表达式的类型和赋值类型不一致,发生编译时错误 ,例如:如果你想实现如下代码:string strTemp ;object obj;....if(strTemp ==  "")          obj   =   DBNull.Value;  else          obj   =   strTemp ;然后为了简单,改成下面这种形式:string strTemp;object obj = strTemp == ""?DBNull.Value:strTemp;你编译的时候,会报错。因为DBNull和string之间没隐式转换,修改成如下代码就可以了:object obj = strTemp == ""? DBNull.Value: (object)strTemp;另外条件操作符是向右关联的,从左到右进行计算,于是a?b:c?d:e 应理解为 a?b:(c?d:e)。上面提到了DBNull,在c#2.0里面实现了Nullable数据类型,别小看这个数据类型,其实非常有用,从此我们就可以放弃对object数据进行 ifobject==null)这样的判断了。同时你会发现,在数据库应用上,数据库中有的字段允许取空值,在C#世界中引入nullable类型正好与之对应,从(C#)对象映射到关系数据库对象,或者反过来,转换都是比较平滑。 为了实现Nullable数据类型转换成non-Nullable型数据,就有了一个这样的操作符”??(两个问号)“,双问号操作符意思是取所赋值??左边的,如果左边为null,取所赋值??右边的,比如int y = x ?? -1 如果x为空,那么y的值为-1.于是这时候就可以把最上面第二段代码改成:string strParam= Request.Params["param"]?? "";嘿嘿,是不是更简洁了。另外还有”?(单问号)“修饰符,是System.Nullable的缩写形式,比如int?代表是可空的整形,例如:int? a = 1 或者 int? b=null。Nullable类型具有一个HasValue的bool类型只读属性,当Nullable类型实例的该属性为true时,则表示该实例是非空实例,包含一个已知值Value,HasValue为false时,访问Value属性将导致System.InvalidOperationException。

C # operator?? And?:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.