C#中is与As运算符号的使用详解
时间:2021-02-13 11:11:13|栏目:.NET代码|点击: 次
如下所示:
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);
}
}
}
}
上一篇:jQuery 插件autocomplete自动完成应用(自动补全)(asp.net后台)
栏 目:.NET代码
下一篇:C#设置输入法实例分析
本文标题:C#中is与As运算符号的使用详解
本文地址:http://www.codeinn.net/misctech/62111.html