is/as操作符,是C#中用于类型转换的,提供了对类型兼容性的判断,从而使得类型转换控制在安全的范畴,提供了灵活的类型转换控制。
is的规则如下:
- 检查对象类型的兼容性,并返回结果,true或者false;
- 不会抛出异常;
- 如果对象为null,则返回值永远为false。
其典型用法为:
object o = new object();
class A
{
}
if (o is A) //执行第一次类型兼容检查
{
A a = (A) o; //执行第二次类型兼容检查
}
as的规则如下:
- 检查对象类型的兼容性,并返回结果,如果不兼容就返回null;
- 不会抛出异常;
- 如果结果判断为空,则强制执行类型转换将抛出NullReferenceException异常。
其典型用法为:
object o = new object();
class B
{
}
B b = o as B; //执行一次类型兼容检查
if (b != null)
{
MessageBox.Show("b is B's instance.");
}
结论
纵上比较,is/as操作符,提供了更加灵活的类型转型方式,但是as操作符在执行效率上更胜一筹;
分享到:
相关推荐
本文实例讲述了C#中is和as的用法,对加深is与as用法的理解有一定的帮助借鉴作用。具体如下: 现来看个例子: public class User { } public class Group { } class Program { static void Main(string[] args) { ...
本文实例分析了C#中is与as的区别,分享给大家供大家参考。具体分析如下: 一、C#类型的转换 在c#中类型的转换分两种:显式和隐式,基本的规则如下: 1、基类对象转化为子类对象,必须显式转换,规则:(类型名) 对象...
在C#中is,as,using关键字具有其特点及使用场景,其中is关键字用于检查该对象是否与给定类型兼容,as关键字用于将对象转换为指定类型,using关键字除了用于引入命名空间之外,还具有回收对象资源,如文件资源、网络...
在程序中,进行类型转换是常见的事,C#支持基本的强制类型转换方法,例如: Object obj1 = new NewType(); NewType newValue = (NewType)obj1; 这样强制转换的时候,这个过程是不安全的,因此需要用try-catch语句...
c#中as和is的用法
主要介绍了C#中的is和as操作符区别小结,is是验证操作对象是不是自己希望的,as是将对象转换成指定类型,需要的朋友可以参考下
本篇文章是对C#中is与As运算符号的使用进行了详细的分析介绍,需要的朋友参考下
NIIT SM2 ISAS C#与JAVA的异同
C# 还提供 is 和 as 运算符来测试值是否属于特定类型。 下面的示例演示如何使用模式匹配 is 语句: class Animal { public void Eat() { Console.WriteLine("Eating."); } public override string ToString() {...
C# in Depth, Second Edition is a thoroughly revised, up-to-date book that covers the new features of C# 4 as well as Code Contracts. In it, you’ll see the subtleties of C# programming in action, ...
C# is a language with the features of C++, programming style like Java and rapid application model of BASIC. If you already know the C++ language, it will take you less than an hour to quickly go ...
Dive in and discover why this Nutshell guide is considered the definitive reference on C#. Get up to speed on the C# language, from the basics of syntax and variables to advanced topics such as ...
Dive in and discover why this Nutshell guide is considered the definitive reference on C#. Get up to speed with all aspects of the C# language, from the basics of syntax and variables, to advanced ...
But when C# is used with .NET Framework 4, the combination is incredibly powerful. This bestselling tutorial shows you how to build web, desktop, and rich Internet applications using C# 4.0 with .NET...
OpenGL is as close as the game indus try has to a stan dard wa y to display graph ics. Whe n the book is finis hed, you’ll have an excellent code base to develop and grow , pursuing your own ideas.
SQL Server is chosen as the main RDBMS, while the database-interface design is demonstrated to work with Oracle as well. The real-life sample application is written in C# using classic Windows Forms....
' -Tomas Restrepo, Microsoft MVP: Visual C++, .NET, and Biztalk Server 'As one of the current designers of C#, it is rare that I learn something new about the language by reading a book. More ...