VB的Dim是否与C#的var相同? [英] Is VB's Dim the same as C#'s var?

查看:53
本文介绍了VB的Dim是否与C#的var相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个小疑问:在VB上,我可以使用Dim声明变量.在C#中,我可以使用 var 进行声明.我对C#的复杂性更加熟悉,并且我知道 var 使用类型推断来确定变量的类型.但是我不确定"Dim"的作用.

This is a small doubt: On VB, I can declare variables using Dim. In C#, I can declare then using var. I'm more familiar with the intricacies of C#, and I know that var uses type inference to determine the type of the variable. But I'm not sure what 'Dim' does.

我似乎这个问题在SO上,但不会同时比较两个关键字.如果有区别,有人可以告诉我哪个吗?

I've seem this question on SO, but it doesn't compare both keywords. If there's a difference, can someone tell me which?

推荐答案

这取决于 Option Infer 已指定.通常,以下是等效的:

That depends if Option Infer is specified. Normally, the following are equivalent:

'VB.Net
Dim myVar
Dim myString = "Hello world!"
Dim myString2 As String = "Hello world!"

//C#
object myVar;
object myString = "Hello world!"; //Notice type is object, *not* string!
string myString2 = "Hello world!";

但是,在启用 Option Infer 的情况下,在同一行上初始化变量时, Dim 变得更像 var :

However, with Option Infer enabled, Dim becomes more like var when the variable is initialized on the same line:

'VB.Net
Option Infer On
Dim myVar
Dim myString = "Hello!"

//C#
object myVar;
var myString = "Hello!"; //Or the equivalent:  string myString = "Hello!";

请注意,这可能会引起一些混乱,因为在声明时突然初始化变量意味着与稍后进行初始化有所不同:

Note that this can lead to some confusion because suddenly initializing a variable at the point of declaration means something different from initializing it later:

'VB.Net
Option Infer On
Dim myVar1
myVar1 = 10
Dim myVar2 = 10

myVar1 = New MyClass() 'Legal
myVar2 = New MyClass() 'Illegal! - Value of type 'MyClass' cannot be converted to 'Integer'

可以通过启用 Option来解决此问题严格 ,它(除其他外)强制在声明时将所有变量赋予类型(隐式或非隐式).

这篇关于VB的Dim是否与C#的var相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆