当前位置: 移动技术网 > IT编程>开发语言>c# > Question:基于C#连续赋值的面试题(解答)

Question:基于C#连续赋值的面试题(解答)

2019年07月18日  | 移动技术网IT编程  | 我要评论
题目在这里:question:基于c#连续赋值的面试题介绍

在msdn中,对=号操作符的说明如下:
image 
赋值运算符 ( =) 将右操作数的值存储在左操作数表示的存储位置、属性或索引器中,并将值作为结果返回。
操作数的类型必须相同(即右操作数必须可以隐式转换为左操作数的类型)。
首先来看
int x,y,z;x = y = z = 1;
.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "courier new", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }
1:z=1,将1赋值给z,接着返回1,
2:y=(z=1),将返回的1赋值给y,并返回1,
3:x=(y=(z=1)),将表达式2的结果1赋值给x。
接着看第一道题:
const int x=1;short y;object z;z=y=x;

首先要说明的是x是const,因为const是编译时常量,所以
z=y=x;在编译的时候就会变成z=y=1。
1:y=1,因为y是short,所以1被转换为short,所以返回值为1(short);
2:将y=1返回的结果,也就是1(short)赋值给z,所以z是1(short)装箱后的对象,
gettype返回system.int16.
值得一提的是,如果你将上面的const int x=1中的const去掉,代码如下:
int x=1;short y;object z;z=y=x;

因为x是int32,y是int16,因为int32无法隐式转换成int16.所以这段代码无法通过编译:
clip_image002
接着考虑第二题:

复制代码 代码如下:

class c
 {
     private string x;
     public string x
     {
         get { return x ?? ""; }
         set { x = value; }
     }
 }

static void main()
{
    c c = new c();
    object z;
    z = c.x = null;

    //下面两句话输出什么
    system.console.writeline(z == null);
    system.console.writeline(c.x == null);
}

关键就是分析:z=c.x=null;

1:c.x=null;调用c的setx方法,设置x=null,并且将null作为值返回。

2:z=(c.x=null);因为c.x=null,返回了null,所以将null赋值给z,z此时为null;

3:console.writeline(z==null),返回true;

4:console.writeline(c.x==null),调用c的getx方法,方法返回””,所以c.x==null,返回false

你都做对了吗?

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网