【发布时间】:2015-06-23 21:17:01
【问题描述】:
在考虑 C# 中的 is 与 as 时,您可以使用其中任何一个来确认一个类型是否可以转换为另一种类型。
// using is
Employee e = new Manager();
if (e is Manager) {
var m = (Manager) e;
// m is now type `Manager`
}
// using as
Employee e = new Manager();
Manager m = e as Manager;
// m is now type `Manager`
if (m != null) {
}
我了解这两个运算符的工作原理以及如何使用它们。考虑is 运算符检查类型两次,而as 检查一次,并且它们都对它们支持的转换类型有相同的限制,是否有使用is 的令人信服的理由?
标记的重复是询问两个运算符之间的区别。我的问题是专门问“了解两者的作用,为什么要使用is?”它们不是同一个问题,也没有相同的答案。
【问题讨论】:
-
你有没有查看过 msdn 网站上关于如何使用 IS 和 AS 安全投射的内容 msdn.microsoft.com/en-us/library/cc488006.aspx
the as operator is more efficient because it actually returns the cast value if the cast can be made successfully. The is operator returns only a Boolean value. It can therefore be used when you just want to determine an object's type but do not have to actually cast it. -
我了解如何使用这两个运算符来安全地转换类型。我更怀疑是否有令人信服的理由使用
is而不是as。 -
我不认为
is转换类型,它只检查它。as投射它。 -
我也了解这两个运营商的工作。我问如果
is检查类型两次而不是检查一次as,是否有理由使用is。
标签: c# type-conversion