[英]Diference between myData as string, (string) myData and Convert.ToString(myData)
I was a little curious to know that what is the difference between using as
keyword , Casting or using Convert.To_______()
function. 我有点好奇知道使用
as
关键字, Casting或使用Convert.To_______()
函数有什么区别。
I after little searching i have found that the as
operator only performs reference conversions and boxing conversions. 经过一点点搜索,我发现
as
运算符只执行引用转换和装箱转换。 What other differences are there. 还有什么其他差异。
I have also noticed that as
keyword is very rarely used why is it so. 我也注意到,
as
关键字很少使用,为什么会如此。 Does any one of them has a performance benefit over other or are they just Redundancy in the Framework. 它们中的任何一个是否具有优于其他的性能优势,或者它们只是框架中的冗余。
The (cast) syntax is very overloaded, and can perform: (强制转换)语法非常重载,可以执行:
"as" performs a subset of these “as”执行这些的子集
But the important feature here is that it doubles as an exception-free test of a type relationship - more efficient than having an exception or testing with reflection. 但是这里的重要特征是它兼作类型关系的无异常测试 - 比使用异常或使用反射测试更有效。 In particular, for example:
特别是,例如:
// is it a list?
IList list = obj as IList
if(list != null) {
// specific code for lists
}
If you strongly believe that an object is something, a (cast) is preferred as this acts as an assertion of your belief. 如果你坚信一个物体是某种东西,那么(演员)是首选,因为这可以作为你信仰的主张。 An exception (in that case) would be desirable.
一个例外(在这种情况下)是可取的。
The Convert methods handle a different range of scenarios including string conversions (otherwise available via things like static .Parse methods) Convert方法处理不同的场景,包括字符串转换(否则可通过静态.Parse方法获得)
If anything, it is Convert that I use least. 如果有的话,它是我最少使用的转换。 The (cast) and "as" syntax is in very regular use.
(强制转换)和“as”语法非常经常使用。
casting vs as: casting throws in exception, as returns null if the conversion cannot be made. cast vs as:cast抛出异常,如果无法进行转换则返回null。 No performance difference whatsoever.
没有任何性能差异。
Convert: entirely different. 转换:完全不同。 You can't cast a number to a string, but you can convert is.
您不能将数字转换为字符串,但您可以转换为。 Read the docs on what the Convert class is capable of.
阅读有关Convert类能够使用的文档。
If you are %100 sure that the object you want to cast will be casted, use Convert, 如果您确定要投射的对象是%100,请使用Convert,
If not use as. 如果不使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.