子类对象可以被当成父类使用,反过来不行
Parent p;
Son c = new Son();
p = c;
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 operator using 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 string 1:not a string 2:'hello' 3:not a string 4:not a string 5:not a stringif (obj is string) { }
复制代码 // 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 Class1 o is Class2 o is neither Class1 nor Class2.