vb.net 使用 DirectCast、CType、TryCast 转换数据类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2703585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:51:05  来源:igfitidea点击:

Casting DataTypes with DirectCast, CType, TryCast

vb.netcastingdirectcastctype

提问by Alex Essilfie

Ever since I moved from VB6 to VB.NET somewhere in 2005, I've been using CType to do casting from one data type to another. I do this because it is simply faster to type, used to exist in VB6 and I do not know why I have to be using DirectCast if there is apparently no difference between them.

自从我在 2005 年从 VB6 迁移到 VB.NET 以来,我一直在使用 CType 进行从一种数据类型到另一种数据类型的转换。我这样做是因为它的输入速度更快,曾经存在于 VB6 中,如果它们之间显然没有区别,我不知道为什么我必须使用 DirectCast。

I use TryCast once in a while because I understand that sometimes casting can fail. I however cannot get the difference between CType and DirectCast.

我偶尔会使用 TryCast,因为我知道有时投射可能会失败。但是我无法区分 CType 和 DirectCast 之间的区别。

Can anyone tell me the difference in plain simple English what the difference the two (CType and DirectCast)? Adding examples of where to use what as well would be helpful.

谁能用简单的英语告诉我两者的区别(CType 和 DirectCast)有什么区别?添加在何处使用什么的示例也会有所帮助。

回答by Hans Passant

TryCast and DirectCast are casting operators that directly map to the CLR's support for casting. They can quickly cast an object of a base type to a derived type or unbox a value of a value type. DirectCast throws an exception when the cast isn't possible, TryCast returns Nothing if it failed. You typically want to favor DirectCast to catch programming mistakes.

TryCast 和 DirectCast 是转换运算符,它们直接映射到 CLR 对转换的支持。它们可以快速地将基类型的对象转换为派生类型或取消装箱值类型的值。DirectCast 在无法进行转换时抛出异常,如果失败,TryCast 将返回 Nothing。您通常希望使用 DirectCast 来捕获编程错误。

CType allows a superset of conversions, ones that the CLR frowns on. The best example I can think of is converting a string to a number or date. For example:

CType 允许转换的超集,CLR 不赞成这些转换。我能想到的最好的例子是将字符串转换为数字或日期。例如:

Dim obj As Object
obj = "4/1/2010"
Dim dt As DateTime = CType(obj, DateTime)

Which you'll have to use if Option Strict On is in effect. If it is Off then you can do it directly:

如果 Option Strict On 生效,您将不得不使用它。如果它是关闭那么你可以直接做到这一点:

Option Strict Off
...
    Dim dt As DateTime = obj

Very convenient of course and part of VB.NET's legacy as a dynamically typed language. But not without problems, that date is Unicorn day at stackoverflow.com but will be a day in January when a Briton enters the string. Unexpected conversions is the reason the CLR doesn't permit these directly. The explicit, never a surprise conversion looks like this:

当然非常方便,并且是 VB.NET 作为动态类型语言的遗产的一部分。但并非没有问题,那个日期是 stackoverflow.com 上的独角兽日,但将是英国人输入字符串的一月份的一天。意外的转换是 CLR 不允许直接进行这些转换的原因。明确的,从不意外的转换如下所示:

Dim dt As DateTime = DateTime.Parse(obj.ToString(), _
    System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat)

Whether you should buy into Try/DirectCast vs CType vs explicit conversions is rather a personal choice. If you now program with Option Strict On then you should definitely start using Try/DirectCast. If you favor the VB.NET language because you like the convenience of dynamic typing then don't hesitate to stay on CType.

您是否应该购买 Try/DirectCast 与 CType 与显式转换是个人选择。如果您现在使用 Option Strict On 进行编程,那么您绝对应该开始使用 Try/DirectCast。如果您喜欢 VB.NET 语言,因为您喜欢动态类型的便利性,那么请不要犹豫,继续使用 CType。

回答by Oded

DirectCast is twice as fast for value types (integers...etc), but identical for reference types.

DirectCast 对于值类型(整数...等)快两倍,但对于引用类型是相同的。

For more information see the "Conversion Functions, CType, DirectCast, and System.Convert" section on thisMSDN page.

有关详细信息,请参阅MSDN 页面上的“转换函数、CType、DirectCast 和 System.Convert”部分。

回答by shahkalpesh

This pageexplains it well.

这个页面很好地解释了它。

Reading it, I think that when you use DirectCast, you are sure that conversion will work without narrowing or expansion (in this case, numeric data). Whereas, CTypewill try to convert to it,with developer being aware of narrowing/expansion.

阅读它,我认为当您使用 时DirectCast,您可以确定转换不会缩小或扩展(在本例中为数字数据)。然而,CType将尝试转换为它,开发人员意识到缩小/扩展。

回答by Vikash Sinha

By "conversion" mean converting one datatype to another (e.g. string to integer, decimal to integer, object to string etc).

“转换”是指将一种数据类型转换为另一种数据类型(例如字符串到整数、十进制到整数、对象到字符串等)。

By "cast" mean changing one type of object into another type that is related to it by one of the following rules.

“强制转换”是指通过以下规则之一将一种类型的对象更改为另一种与其相关的类型。

http://www.thedevheaven.com/2012/09/directcast-vs-ctype.html

http://www.thedevheaven.com/2012/09/directcast-vs-ctype.html