[英]C#: Expensiveness in checking the type of a variable
How expensive is it to check the type of a variable in C#? 在C#中检查变量的类型有多昂贵?
Eg using try
/ catch
vs. using as
vs. using typeof
. 例如,使用
try
/ catch
与使用as
与使用typeof
。
Absolute measurements are not necessary. 绝对测量是不必要的。 :)
:)
try
/ catch
is definitely slower, since a thrown exception causes stack information to be gathered. try
/ catch
绝对慢一些,因为抛出异常会导致堆栈信息被收集。
as
/ is
are for comparing to a type known at compile time and cater for inheritance (ie. "string" is Object
returns true
) as
/ is
用于与在编译时已知的类型进行比较并满足继承要求(即"string" is Object
返回true
)
typeof
/ GetType()
can be used for types known at runtime but do not cater for inheritance (ie. "string".GetType() == typeof(Object)
returns false
) typeof
/ GetType()
可以用于运行时已知的类型,但不能满足继承要求(即"string".GetType() == typeof(Object)
返回false
)
Regardless, I think you probably want as
(or is
if you don't need the cast value) 无论如何,我认为你可能要
as
(或者is
,如果你不需要投值)
Which is expensive is completely irrelevant; 昂贵是完全无关紧要的。 you should never use exception handling as a form of control flow if you can avoid it .
如果可以避免的话,绝对不要将异常处理用作控制流的一种形式 。 It's called "exception handling" because it should only happen in exceptional, unavoidable circumstances .
之所以称为“异常处理”,是因为它只应在特殊的,不可避免的情况下发生。 Invalid type conversion exceptions are bugs and should be fixed.
无效的类型转换异常是错误 ,应予以修复。 Always use "is", "as", or "GetType()" to determine the type of a thing.
始终使用“ is”,“ as”或“ GetType()”来确定事物的类型。
如果只想检查该类型,则应使用is
运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.