博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

4is和as运算符在接口和类中的使用.avi

Posted on 2010-10-15 22:30  EVON168  阅读(180)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IsAndAsDemo
{
    
public interface Italkable
    {
        
void Talk();
    }

    
public class Man:Italkable
    {

        
public void Talk()
        {
            Console.WriteLine(
"男人在说话");
        }
    }

    
public class Duck : Italkable
    {

        
public void Talk()
        {
            Console.WriteLine(
"鸭子嘎嘎叫");
        }
    }

    
public static class Notalk
    {
        
public static void Talk(Italkable target)
        {
            target.Talk();
        }

        
public static void Talk2(object obj)
        {
            Italkable it 
= null;
            
if (obj is Italkable)
            {
                it 
= (Italkable)obj;
                it.Talk();
            }
            
else
            {
                Console.WriteLine(
"类型有误");
            }
        }

        
public static void Talk3(object obj)
        {
            Italkable it 
= null;
            it 
= obj as Italkable;
            
if (it != null)
            {
                it.Talk();
            }
            
else
            {
                Console.WriteLine(
"类型有误");
            }
        }

        
public static void Talk4(object obj)
        {
            Italkable it 
= null;
            
if (obj is Italkable)
            {
                it 
= obj as Italkable;
                it.Talk();
            }
        }
    }

    
class Program
    {
        
static void Main(string[] args)
        {
            Man m 
= new Man();
            Duck d 
= new Duck();
            Notalk.Talk(m);
            Notalk.Talk(d);

            Notalk.Talk2(
1);
            Notalk.Talk2(
"123");
            Notalk.Talk2(m);
            Notalk.Talk2(d);

            Notalk.Talk3(
1);
            Notalk.Talk3(
"123");
            Notalk.Talk3(m);
            Notalk.Talk3(d);
        }
    }
}