C#中is與As運算符號的使用詳解
更新時間:2013年06月09日 10:03:41 作者:
本篇文章是對C#中is與As運算符號的使用進行了詳細的分析介紹,需要的朋友參考下
如下所示:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class IsOrAsClass
{
class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
public override string ToString()
{
return "I am Eating";
}
}
//家禽類
class jia:Animal
{
}
//狗
class Dog : jia
{
}
//鳥
class bird
{
}
static void Main()
{
IsOrAsClass app=new IsOrAsClass();
//
Dog d=new Dog();
app.UseIsOpreate(d);
app.UseAsOpreate(d);
//
bird b = new bird();
app.UseAsOpreate(b);
}
//使用Is運算符
void UseIsOpreate(Animal a)
{
if (a is jia)
{
jia j = (jia)a;
j.Eat();
}
}
//使用AS運算符
void UseAsOpreate(object o)
{
jia j = o as jia;
if (j != null)
{
Console.WriteLine(j.ToString());
}
else
{
Console.WriteLine("{0} is not Animal", o.GetType().Name);
}
}
}
}
復制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class IsOrAsClass
{
class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
public override string ToString()
{
return "I am Eating";
}
}
//家禽類
class jia:Animal
{
}
//狗
class Dog : jia
{
}
//鳥
class bird
{
}
static void Main()
{
IsOrAsClass app=new IsOrAsClass();
//
Dog d=new Dog();
app.UseIsOpreate(d);
app.UseAsOpreate(d);
//
bird b = new bird();
app.UseAsOpreate(b);
}
//使用Is運算符
void UseIsOpreate(Animal a)
{
if (a is jia)
{
jia j = (jia)a;
j.Eat();
}
}
//使用AS運算符
void UseAsOpreate(object o)
{
jia j = o as jia;
if (j != null)
{
Console.WriteLine(j.ToString());
}
else
{
Console.WriteLine("{0} is not Animal", o.GetType().Name);
}
}
}
}
相關文章
C#中使用Join與GroupJoin將兩個集合進行關聯(lián)與分組
這篇文章主要介紹了C#中使用Join與GroupJoin將兩個集合進行關聯(lián)與分組,文中分別對Join和GroupJoin的用法進行詳細說明,需要的朋友可以參考下2017-12-12解析c#在未出現(xiàn)異常情況下查看當前調用堆棧的解決方法
本篇文章是對c#在未出現(xiàn)異常情況下查看當前調用堆棧的解決方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05