C# 在visual basic中铸造?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/748725/
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-08-04 23:40:26  来源:igfitidea点击:

Casting in visual basic?

c#vb.netcasting

提问by Kredns

I'm a C# programmer who is forced to use VB (eh!!!!). I want to check multiple controls state in one method, in C# this would be accomplished like so:

我是一名被迫使用 VB 的 C# 程序员(嗯!!!!)。我想用一种方法检查多个控件状态,在 C# 中,这将像这样完成:

if (((CheckBox)sender).Checked == true)
{
    // Do something...
}
else
{
    // Do something else...
}

So how can I accomplish this in VB?

那么我怎样才能在 VB 中做到这一点呢?

采纳答案by Adam Robinson

C#:

C#:

(CheckBox)sender

VB:

VB:

CType(sender, CheckBox)

回答by Andrew Hare

Adam Robinsonis correct, also DirectCastis available to you.

Adam Robinson是正确的,也DirectCast可供您使用。

回答by JaredPar

VB actually has 2 notions of casting.

VB 实际上有 2 个强制转换的概念。

  1. CLR style casting
  2. Lexical Casting
  1. CLR 风格铸造
  2. 词法转换

CLR style casting is what a C# user is more familiar with. This uses the CLR type system and conversions in order to perform the cast. VB has DirectCast and TryCast equivalent to the C# cast and as operator respectively.

CLR 样式转换是 C# 用户更熟悉的。这使用 CLR 类型系统和转换来执行强制转换。VB 的 DirectCast 和 TryCast 分别相当于 C# cast 和 as 运算符。

Lexical casts in VB do extra work in addition to the CLR type system. They actually represent a superset of potential casts. Lexical casts are easily spotted by looking for the C prefix on the cast operator: CType, CInt, CString, etc ... These cast, if not directly known by the compiler, will go through the VB run time. The run time will do interpretation on top of the type system to allow casts like the following to work

除了 CLR 类型系统之外,VB 中的词法转换还做了额外的工作。它们实际上代表了潜在演员的超集。通过查找强制转换运算符上的 C 前缀很容易发现词法强制转换:CType、CInt、CString 等……这些强制转换,如果编译器不直接知道,将通过 VB 运行时。运行时将在类型系统之上进行解释,以允许像下面这样的强制转换工作

Dim v1 = CType("1", Integer)
Dim v2 = CBool("1")

回答by Ben

DirectCast will perform the conversion at compile time but can only be used to cast reference types. Ctype will perform the conversion at run time (slower than converting at compile time) but is obviously useful for convertng value types. In your case "sender" is a reference type so DirectCast would be the way to go.

DirectCast 将在编译时执行转换,但只能用于转换引用类型。Ctype 将在运行时执行转换(比在编译时转换慢)但显然对 convertng 值类型很有用。在您的情况下,“发件人”是一种引用类型,因此 DirectCast 将是要走的路。

回答by Lolu Omosewo

Casting in VB.net uses the keyword ctype. So the C# statement (CheckBox)senderis equivalent to ctype(sender,CheckBox)in VB.net.

VB.net 中的转换使用关键字ctype。所以C#语句(CheckBox)sender相当于ctype(sender,CheckBox)VB.net中的。

Therefore your code in VB.net is:

因此,您在 VB.net 中的代码是:

if ctype(sender,CheckBox).Checked =True Then
    ' Do something...
else
    ' Do something else...
End If