上周参加面试,一道c#面试题很简单,面试官三问两问就蒙圈了,回来自己验证一下,才搞明白,汗~总结下:
①如下程序输出:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int t; 6 string str; 7 Console.WriteLine("t={0},str={1}",t,str); //问:输出什么? 8 9 Console.Read(); 10 } 11 }
②如下程序输出:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 B b=new B(); 6 b.Test(); 7 Console.Read(); 8 } 9 } 10 11 public class A 12 { 13 public A() 14 { 15 Test(); 16 } 17 public virtual void Test() { } 18 } 19 20 public class B : A 21 { 22 int x; 23 int y; 24 string s; 25 26 public B() 27 { 28 x = 1; 29 } 30 public override void Test() 31 { 32 Console.WriteLine("x={0},y={1},s={2}", x, y, s); 33 } 34 }
答案:1题程序直接报错:使用了未赋值的局部变量
2题: x=0,y=0,s=
x=1,y=0,s=
2题还涉及实例化子类实例时调用父类构造器的问题,重点比较下1、2中涉及到的两种变量:
1中声明的变量为局部变量(方法中声明),不会自动初始化,直接调用会报错:使用了未赋值的局部变量
2中声明的变量为实例变量(类中声明),会自动初始化,int默认0,string默认空字符串。
延伸:修改B类为如下代码:
1 public class B : A 2 { 3 public int x; 4 int y; 5 string s; 6 7 public B() 8 { 9 x = 1; 10 } 11 public override void Test() 12 { 13 int t1; 14 int t2 = 2; 15 string str2 = "hello"; 16 Console.WriteLine("x={0},y={1},s={2}", x, y, s); 17 } 18 }
编译,通过.net reflector反编译查看该类,为如下代码:
得到如下结论:
1>缺省访问限制符的实例变量,其访问限制为private,即只能类中访问
2>实例变量的引用,类中可以用this(当前对象)引用,声明为public的变量,类外可以用 实例.实例变量的格式 (如:new B().x )
3>局部变量,如B中的t1,t2,str2,如果没有被引用,是不会被编译进dll的,因为反编译后未发现它们的影子
后记:这次面试让我感慨,基础知识很重要,有时候不必懂得多么高深的技术,基础扎实了,也能也出不错的程序