我是一位经验丰富的C/C++/C#程序员,刚刚进入VB.NET.我通常使用CType(和CInt,CBool,CStr)进行演员表示,因为它是较少的字符,并且是我接触的第一种投射方式,但我也知道DirectCast和TryCast.
简单来说,DirectCast和CType之间是否有任何差异(演员,表演等的影响)?我理解TryCast的想法.
C#是否与VB.NET的DirectCast等效?
我知道它有()强制转换和'as'关键字,但那些符合CType和TryCast.
需要说明的是,这些关键字执行以下操作:
CType /()强制转换:如果它已经是正确的类型,则强制转换它,否则查找类型转换器并调用它.如果未找到类型转换器,则抛出InvalidCastException.
TryCast /"as"关键字:如果是正确的类型,则抛出它,否则返回null.
DirectCast:如果它是正确的类型,则抛出它,否则抛出InvalidCastException.
在我详细说明之后,有些人仍然回答说()是等价的,所以我会进一步扩展为什么这不是真的.
DirectCast仅允许在继承树上缩小或扩展转换.它不支持像()那样跨不同分支的转换,即:
C# - 这个编译并运行:
//This code uses a type converter to go across an inheritance tree
double d = 10;
int i = (int)d;
Run Code Online (Sandbox Code Playgroud)
VB.NET - 这不是编译
'Direct cast can only go up or down a branch, never across to a different one.
Dim d As Double = 10
Dim i As Integer = DirectCast(d, Integer)
Run Code Online (Sandbox Code Playgroud)
VB.NET与我的C#代码的等价物是CType:
'This compiles and runs
Dim d As Double = …Run Code Online (Sandbox Code Playgroud) 为什么这在VB.Net中有效:
Dim ClipboardStream As New StreamReader(
CType(ClipboardData.GetData(DataFormats.CommaSeparatedValue), Stream))
Run Code Online (Sandbox Code Playgroud)
但这是在C#中抛出一个错误:
Stream是一个Type,在当前上下文中无效
ClipboardStream = new StreamReader(Convert.ChangeType(
ClipboardData.GetData(DataFormats.CommaSeparatedValue), Stream));
Run Code Online (Sandbox Code Playgroud)
说实话,我不是100%在转换类型上,我只是在代码片段中使用过它们,现在我正在尝试将简单的VB代码片段转换为C#版本...