普通类型转换和使用“AS”关键字有什么区别
可能重复:
直接投射vs’as’运算符?
转换:( NewType)与Object为NewType
正常的类型转换和使用“AS”关键字有什么区别?
如果对象是错误的类型,则使用as
将正常失败,并且结果值将为null,其中正常转换将抛出InvalidCastException:
object x = new object(); string y = x as string; // y == null string z = (string)x; // InvalidCastException
两个运算符的用例表面上相似,但在语义上完全不同。 演员与读者沟通“我确信这种转换是合法的,如果我错了,我愿意接受运行时exception”。 “as”操作员传达“我不知道这种转换是否合法;我们将试一试,看看它是怎么回事”。
有关此主题的更多信息,请参阅我关于此主题的文章:
as
施放会引发exception,而通常的施法可以。
Object a = new Object(); String b = a as String; if(b != null) // always false for this example. {}
普通类型转换可能会返回IllegalTypeCastexception,因为在这种情况下as
将返回null
。
((Class2) obj) // Throws exception when the casting cannot be made Class2 C = obj as Class2 // Will return NULL if the casting cannot be made
如果您使用“as”关键字,则永远不会获得转换exception。 如果您尝试无效转换,则转换结果将为null
。
可以在具有inheritance/实现关系的类/接口之间使用隐式/显式转换,否则会产生编译错误。 见例子:
public class A {} public class B {} ... A a = new A(); //B b = (B)a; //compile error:Cannot implicitly convert type 'A' to 'B'
隐式/显式转换的另一种情况是A类和B类之间没有关系,但您自己编写了一个隐式 / 显式运算符。
此外,因为只能与引用类型一起使用。 这实际上非常合乎逻辑,因为如果转换失败,则返回false,这不是值类型的可能值。
因此,对于值类型,必须使用正常的类型转换。
as
不能与值类型(非可空类型)一起使用。
对于参考类型……
expression as type
真是一样的
expression is type ? (type) expression : (type) null
除了expression
只被评估一次。
在向比尔克林顿致敬时,’is’在’表达是类型’中,我的意思是’ 是 ‘。
基本上,正如其他答案所示,这意味着当演员表失败时返回null。 但是,当转换成功但类型错误时,它也会返回null。
这是一个有点愚蠢的例子:
uint? u = 52; int? i = (int?) u; // 'i' is now 52
但
uint? u = 52; object d = u; int? i = d as int?;
我有什么价值? 52? 不。 它是null。
为什么那里的物体? 当我用’是’解释’as’时,原来我撒谎了。
注意:
uint? u = 52; int? i = (u is int?) ? (int?) u : (int?) null;
‘我’现在为null
uint? u = 52; int? i = u as int?;
哎呀。 编译错误。 所以,我猜这两个陈述毕竟不完全相同。