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# List<T>的Contains,Exists,Any,Where性能对比
这篇文章主要介绍了详解C# List<T>的Contains,Exists,Any,Where性能对比,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-12-12
C#解决多IfElse判断语句和Switch语句问题的方法分享
这篇文章主要为大家介绍C#如何使用设计模式中的策略模式和委托来解决多个IfElse判断语句和Switch语句,这种替换方式在其他语言也一样可以做到,感兴趣的可以了解一下2022-12-12


最新评论