// 不编译, 预测一下这个程序输出什么. 不要偷偷地编译哦 :)class Test
{
  System.Windows.Forms.TextBox ctl;  Test()
  {
    System.Console.WriteLine(ctl is System.Windows.Forms.TextBoxBase);
  }  static void Main()
  {
    new Test();
  }
}

解决方案 »

  1.   

    true, "is" 可以识别他们的"种族"
      

  2.   

    System.Windows.Forms.TextBox ctl;
    ctl对象没有实例化,所以其值为null,所以 System.Console.WriteLine(ctl is System.Windows.Forms.TextBoxBase);值为false。如果是System.Windows.Forms.TextBox ctl = new TextBox();
    System.Console.WriteLine(ctl is System.Windows.Forms.TextBoxBase);值为true.
      

  3.   

    /*
    题目所给的程序编译时会有两个警告, 先看看第1个, 是关于 (ctl is TextBoxBase) 表达式的:
    warning CS0183: The given expression is always of the provided ('TextBoxBase') type这是因为编译器看到 ctl 是 TextBox, 始终为 TextBoxBase 类型, 所以给出了警告.MSDN 关于 "is 运算符" 的论述中说到:
    如果已知 expression is type 表达式总是为 true 或总是为 false, 则会发出编译时警告.程序如下改写, 则可以消除这个编译时警告.
    */using System.Windows.Forms;class Test
    {
      TextBox ctl;  Test()
      {
        System.Console.WriteLine(IsTextBoxBase(ctl));
      }  bool IsTextBoxBase(Control c)
      {
        return c is TextBoxBase;
      }  static void Main()
      {
        new Test();
      }
    }
      

  4.   

    编译时有下面的警告:
    警告等级 4 CS0649:从未对字段“Test.ctl”赋值,字段将一直保持其默认值 null
    警告等级 1 CS0183:给定表达式始终为所提供的(“System.Windows.Forms.TextBoxBase”)类型输出 False,因为 ctl 没有被实例化。
      

  5.   

    第2个编译时警告是:
    warning CS0649: Field 'Test.ctl' is never assigned to, and will always have its default value null因为 ctl = null, 而 null is not TextBoxBase, 故程序将输出 False
    如 linuxyf 所言, 如果是 TextBox ctl = new TextBox(); 则程序将输出 True