080313

来源:互联网 发布:pdf reader for mac 编辑:程序博客网 时间:2024/05/21 22:56

子类对象可以被当成父类使用,反过来不行

 

Parent p;
Son c
=new Son();
p
=c;

 

as AND is

The as operator is used to perform conversions between compatible types. (兼容类型)The as operator is used in an expression of the form:

 

 

expression as type

is equivalent to:

expression is type ? (type)expression : (type)null
 
// cs_keyword_as.cs// The as operatorusing System;class MyClass1 {}class MyClass2 {}public class IsTest {   public static void Main()    {      object [] myObjects = new object[6];      myObjects[0] = new MyClass1();      myObjects[1] = new MyClass2();      myObjects[2] = "hello";      myObjects[3] = 123;      myObjects[4] = 123.4;      myObjects[5] = null;      for (int i=0; i<myObjects.Length; ++i)       {         string s = myObjects[i] as string;         Console.Write ("{0}:", i);         if (s != null)            Console.WriteLine ( "'" + s + "'" );         else            Console.WriteLine ( "not a string" );      }   }}
 
0:not a string1:not a string2:'hello'3:not a string4:not a string5:not a string
 
 
 
 
if (obj is string){}
 
 CopyCode image复制代码
// cs_keyword_is.cs// The is operator.using System;class Class1{}class Class2{}class IsTest{    static void Test(object o)    {        Class1 a;        Class2 b;        if (o is Class1)        {            Console.WriteLine("o is Class1");            a = (Class1)o;            // Do something with "a."        }        else if (o is Class2)        {            Console.WriteLine("o is Class2");            b = (Class2)o;            // Do something with "b."        }        else        {            Console.WriteLine("o is neither Class1 nor Class2.");        }    }    static void Main()    {        Class1 c1 = new Class1();        Class2 c2 = new Class2();        Test(c1);        Test(c2);        Test("a string");    }}
 

输出

 
o is Class1o is Class2o is neither Class1 nor Class2.