080313

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

 

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 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 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 Class1
o is Class2
o is neither Class1 nor Class2.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值