VB.NET 教程_01_基础语法

 

 

VB.Net教程简介:

VB.Net是一种简单,现代,面向对象的计算机编程语言,由微软开发,将.NET Framework和公共语言运行库的强大功能与做为Visual Basic标志的生产力优点相结合。git

Visual Basic .NET(VB.NET)是在.NET Framework上实现的面向对象的计算机编程语言。 虽然它是经典的Visual Basic语言的演变,可是它不兼容VB6,在任何旧版本编写的代码不能在VB.NET下编译。 
像全部其余.NET语言同样,VB.NET彻底支持面向对象的概念。 VB.NET中的一切都是一个对象,包括全部的基本类型(Short,Integer,Long,String,Boolean等)和用户定义的类型,事件,甚至是程序集。 全部对象从基类Object继承。
VB.NET是由Microsoft的.NET框架实现的。 所以,它能够彻底访问.Net框架中的全部库。 也能够在Mono上运行VB.NET程序,Mono是.NET的开源替代软件,不只在Windows下,甚至在Linux或Mac OSX上。  程序员

 

如下缘由使VB.Net成为普遍使用的专业语言:数据库

  • 现代,通用。
  • 面向对象。
  • 面向组件。
  • 简单易学。
  • 结构化的语言。
  • 它产生高效的程序。
  • 它能够在各类计算机平台上进行编译。
  • .NET Framework(框架)的一部分。

VB.Net强大的编程功能

VB.Net有许多强大的编程功能,使世界各地的程序员都很喜欢使用它。 让咱们看一下这些功能:express

  • 布尔条件
  • 自动垃圾回收
  • 标准库
  • 程序集版本控制
  • 属性和事件
  • 委托和事件管理
  • 易于使用泛型
  • 索引器
  • 条件编译
  • 简单的多线程

本教程将教你基本的VB.Net编程,也将带你学习与VB.Net编程语言相关的各类高级概念。编程

本教程是为初学者准备的,帮助他们了解基本的VB.Net编程。 完成本教程后,您将发现本身在VB.Net编程中达到一个中等水平的专业知识,你能够从本身经过其余方式学习到下一个级别。api

 

在您开始学习本教程以前须要先学习如下知识:数组

VB.Net 编程很大程度基于 BASIC 和 Visual Basic 编程语言,因此若是你对这些编程语言有基本的了解而后再学习VB.Net你会发现 VB.Net 编程语言的乐趣。服务器

 

版本历史:

Visual Basic .NET 2002多线程

2002年Visual Basic .NET 问世,此后Visual Basic 包含在 Visual Studio套装中。该版本又被称为VB 7.0,是与C#一块儿在2002年发布的最初始的VB.net版本。C#是一门新设计.Net语言而且语法上和Java有必定的类似性,因此被大力宣传为微软对付JAVA的王牌,受到媒体极力关注。然而VB.NET则相反被错误地认为仅仅是VB的一个升级(故有时被称为VB7),它的受关注度也所以较低,固然VB社区以及喜欢Basic系列风格的语言的人仍是很关注它的。那些试用过此版VB.NET的人在层层幕布下发现一个强大却艰深的语言。不过任何一种语言都是有弱点的,固然后面这一点也是.NET语言的共性,那就是运行的计算机上必须装相应版本的.Net framework。app

 

Visual Basic .NET 2003

该版本是和.NET Framework 1.1一块儿发布的。新功能包括对.NET Compact Framework的支持和更好的VB升迁向导。并改进了运行情况,IDE稳定性(尤为是后台编译器),以及运行时RunTime稳定性。另外,VB.NET2003还有一个学院版Visual Studio .NET 2003 Academic Edition (VS03AE),它是分发给各国某些学者无偿使用的版本。

 

Visual Basic .NET 2005

该版本是VB.Net的重大转变。可是这个版本的 Visual Studio 仍然仍是面向 .NET 框架的(版本2.0)。它同时也能开发跨平台的应用程序,如开发使用微软操做系统的手机的程序等。整体来讲是一个很是庞大的软件,甚至包含代码测试功能。

 

Visual Basic .NET 2008

Visual Basic 2008于2008年2月1日发布。经过几年的发展,它已成为一种专业化的开发语言和环境。用户可用 Visual Basic 快速建立 Windows 程序,如今还能够编写企业水平的客户/服务器程序及强大的数据库应用程序。

 

Visual Studio 2010

Visual Studio 2010于2010年4月12日上市,其中包含 Visual Basic .NET 2010 。Visual Studio是微软公司推出的开发环境。是目前最流行的Windows平台应用程序开发环境。Visual Studio 2010集成开发环境(IDE)的界面被从新设计和组织,变得更加简单明了。Visual Studio 2010同时带来了 NET Framework 4.0、Microsoft Visual Studio 2010 CTP( Community Technology Preview--CTP),而且支持开发面向Windows 7的应用程序。除了Microsoft SQL Server,它还支持 IBM DB2和Oracle数据库等。

 

Visual Studio 2012

从该版本开始VB.NET已没有单独发售的IDE了,微软给Visual Basic .NET 以及C#开发者的IDE就只有Visual Studio 了。该版本增长了modern(原metro)风格的支持等众多新特性。

 

Visual Studio 2015

增长了大量新特性,提高你的编写效率。对编译器和开发环境优化,提升编译速度,帮你重构代码和解决错误。最明显的14项改进见参考资料的14 Top Improvements in Visual Basic 14。

 

VB关系

不能简单认为VB .net是VB的新版本。首先它们一个是彻底面向对象的语言,而另外一个不是彻底面向对象的,其次VB .NET是构建于.Net framework之上的。固然,它们同属Basic系列语言,又同为微软所开发,语法上有必定的类似或沿袭是很正常的,但不能所以认为VB .NET是VB的升级版。

对于想从VB转到VB .NET的开发者来讲,若是你只是喜欢Basic系列语言的代码风格,那么你的迁移会很顺利,若是你想沿袭以前VB的编程思想和习惯,你会很苦恼,缘由之一就是VB .NET贯穿的是彻底面向对象的思想,而VB不是。

微软为使VB开发者更容易转到VB .NET,兼容一些VB6函数和库的用法,可是比不上.NET语言中自带的可替换的函数和库来得高效,因此咱们应该尽可能使用.NET下的新方法。微软还提供了VB到VB .NET的自动转换器,虽几经改进,但仍没法转换所有代码,几乎全部非小型程序都须要人工修改以完成编译。为了运行优化,大多程序须要大量工做去重构。

 

争议与解释:许多资深的VB程序员抱怨VB .NET,由于VB .NET丢掉了许多再也不发行的VB6中使用的大量语言constructs和用户界面功能,而且对保留下来的东西也改变了语意。其实不该该再把VB和VB .NET作功能上的比较,由于它们除了有些语法类似外,能够说是彻底不一样的两种语言。

Visual Basic .NET与VB都表明了Basic系列语言的编码风格,Visual Basic .NET是这种编码风格在.NET平台上的继承,而不是同系列语言VB的沿袭。

VB.Net教程结构概述:

本教程共由3个章节构成,详细讲述了vb.net的基础使用方法并附带了大量示例辅助您的学习,让您轻松掌握VB .Net。

本教程包含:

一、《VB.Net教程-基础语法》

二、《VB.Net教程-常见对象》

三、《VB.Net教程-面向对象》

四、《VB.Net教程-高级教程》
 

 

VB.Net - 环境设置

 

在本章中,咱们将讨论可用于建立VB.Net应用程序的工具。

咱们已经提到VB.Net是.Net框架的一部分,用于编写.Net应用程序。 所以,在讨论用于运行VB.Net程序的可用工具以前,让咱们先了解VB.Net如何与.Net框架相关。

.NET框架 

.NET Framework是一个革命性的平台,能够帮助你编写如下类型的应用:

  • Windows应用程序

  • Web应用程序

  • 网页服务

 

.Net框架应用程序是多平台应用程序。 该框架的设计方式使其能够从如下任何语言使用:Visual Basic,C#,C ++,Jscript和COBOL等。

 

.Net框架包含一个巨大的代码库,用于客户端语言(如VB.Net)。 这些语言使用面向对象的方法。

 

全部这些语言能够访问框架以及彼此通讯。

 

 

如下是.Net框架的一些组件:

 

  • 公共语言运行时(CLR)  Common Language Runtime (CLR)

  • .NET框架类库  The .Net Framework Class Library

  • 公共语言规范  Common Language Specification

  • 通用类型系统  Common Type System

  • 元数据和组件  Metadata and Assemblies

  • Windows窗体  Windows Forms

  • ASP.Net和ASP.Net AJAX  

  • ADO.Net

  • Windows工做流基础(WF)  Windows Workflow Foundation (WF)

  • Windows演示基础  Windows Presentation Foundation

  • Windows通信基础(WCF)  Windows Communication Foundation (WCF)

  • LINQ

 

有关每一个组件的详细信息,请参阅微软的文档。

 

VB.Net的集成开发环境(IDE) 

 

Microsoft为VB.Net编程提供如下开发工具:

一、Visual Studio 2010(VS)

 

二、Visual Basic 2010 Express(VBE)

 

三、可视化Web开发

 

最后两个是免费的。 使用这些工具,您能够将各类VB.Net程序从简单的命令行应用程序写入到更复杂的应用程序。 Visual Basic Express和Visual Web Developer Express版是Visual Studio的精简版本,具备相同的外观和感受。 它们保留了Visual Studio的大多数功能。 在本教程中,咱们使用了Visual Basic 2010 Express和Visual Web Developer(针对Web编程章节)。

 

它会自动安装在您的计算机上。 请注意,您须要一个有效的互联网链接安装快速版本。

 

在Linux或Mac OS上编写VB.Net程序

 

虽然.NET Framework在Windows操做系统上运行,但有一些替代版本可在其余操做系统上运行。 Mono是.NET Framework的开源版本,包括Visual Basic编译器,可在多种操做系统上运行,包括各类Linux和Mac OS。 最新版本是VB 2012。

Mono的既定目的不只是可以跨平台运行Microsoft .NET应用程序,并且为Linux开发人员提供更好的开发工具。 Mono能够在许多操做系统上运行,包括Android,BSD,iOS,Linux,OS X,Windows,Solaris和UNIX。

 

 

VB.Net - 程序结构

 

在咱们学习VB.Net编程语言的基本构建块以前,让咱们看看一个最小的VB.Net程序结构,以便咱们能够将它做为将来的章节的参考。

 

VB.Net Hello World示例

一个VB.Net程序主要由如下几部分组成:

  • 命名空间声明  Namespace declaration

  • 一个类或模块  A class or module

  • 一个或多个程序  One or more procedures

  • 变量  Variables

  • 主过程  The Main procedure

  • 语句和表达式  Statements & Expressions

  • 注释  Comments

 

让咱们看一个简单的代码,打印单词“Hello World”:

Imports System
Module Module1
   'This program will display Hello World 
   Sub Main()
      Console.WriteLine("Hello World")
      Console.ReadKey()
   End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果:

Hello, World!

让咱们来看看上面的程序中的各个部分:

  • 程序Imports System的第一行用于在程序中包括系统命名空间。The first line of the program Imports System is used to include the System namespace in the program.

  • 下一行有一个Module声明,模块Module1。 VB.Net是彻底面向对象的,因此每一个程序必须包含一个类的模块,该类包含您的程序使用的数据和过程。The next line has a Module declaration, the module Module1. VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses.

  • 类或模块一般将包含多个过程。 过程包含可执行代码,或者换句话说,它们定义了类的行为。 过程能够是如下任何一种:

    • 功能 Function

    • 子 Sub

    • 运算符 Operator

    • 获取 Get

    • 组 Set

    • AddHandler

    • RemoveHandler

    • 的RaiseEvent

     

  • 下一行('这个程序)将被编译器忽略,而且已经在程序中添加了额外的注释。

  • 下一行定义了Main过程,它是全部VB.Net程序的入口点。 Main过程说明了模块或类在执行时将作什么。

  • Main过程使用语句指定其行为

    Console.WriteLine(“Hello World”的)

    WriteLine是在System命名空间中定义的Console类的一个方法。 此语句会致使消息"Hello,World !"在屏幕上显示。

     

  • 最后一行Console.ReadKey()是用于VS.NET用户的。 这将阻止屏幕从Visual Studio .NET启动时快速运行和关闭。

编译和执行VB.Net程序:

若是您使用Visual Studio.Net IDE,请执行如下步骤:

  • 启动Visual Studio。 Start Visual Studio.

  • 在菜单栏,选择文件,新建,项目。 On the menu bar, choose File, New, Project.

  • 从模板中选择Visual Basic。Choose Visual Basic from templates

  • 选择控制台应用程序。Choose Console Application.

  • 使用浏览按钮指定项目的名称和位置,而后选择肯定按钮。 Specify a name and location for your project using the Browse button, and then choose the OK button.

  • 新项目显示在解决方案资源管理器中。 The new project appears in Solution Explorer.

  • 在代码编辑器中编写代码。 Write code in the Code Editor.

  • 单击运行按钮或F5键运行项目。 将出现一个包含行Hello World的命令提示符窗口。 Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World.

 

您可使用命令行而不是Visual Studio IDE编译VB.Net程序:

  • 打开文本编辑器,并添加上述代码。 Open a text editor and add the above mentioned code.

  • 将文件另存为helloworld.vb。 Save the file as helloworld.vb

  • 打开命令提示符工具并转到保存文件的目录。 Open the command prompt tool and go to the directory where you saved the file.

  • 类型VBC helloworld.vb,而后按回车编译代码。 Type vbc helloworld.vb and press enter to compile your code.

  • 若是在你的代码中没有错误命令提示符下会带你到下一行,并会产生HelloWorld.exe的可执行文件。 If there are no errors in your code the command prompt will take you to the next line and would generate helloworld.exe executable file.

  • 接下来,输入的HelloWorld来执行你的程序。 Next, type helloworld to execute your program.

  • 您将能够看到“Hello World”字样在屏幕上。 You will be able to see "Hello World" printed on the screen.

 

 

VB.Net - 基本语法

 

VB.Net是一种面向对象的编程语言。 在面向对象编程方法中,程序由经过动做相互交互的各类对象组成。 对象可能采起的动做称为方法。 相同类型的对象被认为具备相同的类型,或者更常常地被称为在同一类中。

 

当咱们考虑VB.Net程序时,它能够定义为经过调用对方的方法进行通讯的对象的集合。 如今让咱们简单地看看类,对象,方法和实例变量是什么意思。

 

  • Object 对象 -对象具备状态和行为。 示例:狗有状态 - 颜色,名称,品种以及行为 - 摇摆,吠叫,吃饭等。对象是类的实例。Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class.

  • Class  -类能够被定义为描述其类型的对象支持的行为/状态的模板/蓝图。A class can be defined as a template/blueprint that describes the behaviors/states that objects of its type support.

  • Methods 方法 -方法基本上是一种行为。 一个类能够包含许多方法。 它是在写逻辑,操纵数据和执行全部动做的方法中。A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

  • 实例变量 -每一个对象都有其惟一的实例变量集。 对象的状态由分配给这些实例变量的值建立。Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

 

VB.Net中的Rectangle类

例如,让咱们考虑一个Rectangle对象。 它具备长度和宽度等属性。 根据设计,它可能须要接受这些属性的值,计算面积和显示细节的方式。

 

让咱们看一个Rectangle类的实现,并在咱们的观察的基础上讨论VB.Net基本语法:

Imports System
Public Class Rectangle
    Private length As Double
    Private width As Double

    'Public methods
    Public Sub AcceptDetails()
        length = 4.5
        width = 3.5
    End Sub

    Public Function GetArea() As Double
        GetArea = length * width
    End Function
    Public Sub Display()
        Console.WriteLine("Length: {0}", length)
        Console.WriteLine("Width: {0}", width)
        Console.WriteLine("Area: {0}", GetArea())

    End Sub

    Shared Sub Main()
        Dim r As New Rectangle()
        r.Acceptdetails()
        r.Display()
        Console.ReadLine()
    End Sub
End Class

 

当上述代码被编译和执行时,它产生如下结果:

Length: 4.5
Width: 3.5
Area: 15.75

在上一章中,咱们建立了一个包含代码的Visual Basic模块。 Sub Main表示VB.Net程序的入口点。 这里,咱们使用包含代码和数据的类。 您使用类来建立对象。 例如,在代码中,r是一个Rectangle对象。

 

对象是类的一个实例:

Dim r As New Rectangle()

 

类能够具备能够从外部类访问的成员,若是指定的话。 数据成员称为字段,过程成员称为方法。

能够在不建立类的对象的状况下调用共享方法或静态方法。 经过类的一个对象调用实例方法:

 

Shared Sub Main()
   Dim r As New Rectangle()
   r.Acceptdetails()
   r.Display()
   Console.ReadLine()
End Sub

 

标识符

标识符是用于标识类,变量,函数或任何其余用户定义项的名称。 在VB.Net中命名类的基本规则以下:

  • 名称必须以字母开头,后跟一个字母,数字(0 - 9)或下划线。 标识符中的第一个字符不能是数字。A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.

  • 它不能包含任何嵌入的空格或符号是怎样的?  - +! @#%^&*()[] {}。 ; :“'/和\。可是,可使用下划线(_)。It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.

  • 它不该该是保留关键字。It should not be a reserved keyword.

 

VB.Net关键字

下表列出了VB.Net保留的关键字:

AddHandler AddressOf Alias And AndAlso As Boolean
ByRef Byte ByVal Call Case Catch CBool
CByte CChar CDate CDec CDbl Char CInt
Class CLng CObj Const Continue CSByte CShort
CSng CStr CType CUInt CULng CUShort Date
Decimal Declare Default Delegate Dim DirectCast Do
Double Each Else ElseIf End End If Enum
Erase Error Event Exit False Finally For
Friend Function Get GetType

GetXML

Namespace

Global GoTo
Handles If Implements Imports In Inherits Integer
Interface Is IsNot Let Lib Like Long
Loop Me Mod Module MustInherit MustOverride MyBase
MyClass Namespace Narrowing New Next Not Nothing

Not

Inheritable

Not

Overridable

Object Of On Operator Option
Optional Or OrElse Overloads Overridable Overrides ParamArray
Partial Private Property Protected Public RaiseEvent ReadOnly
ReDim REM

Remove

Handler

Resume Return SByte Select
Set Shadows Shared Short Single Static Step
Stop String Structure Sub SyncLock Then Throw
To True Try TryCast TypeOf UInteger While
Widening With WithEvents WriteOnly Xor

 

 

 

VB.Net - 数据类型

 

数据类型指用于声明不一样类型的变量或函数的扩展系统。 变量的类型肯定它在存储中占用多少空间以及如何解释存储的位模式。

VB.Net中提供的数据类型

VB.Net提供了多种数据类型。下表显示的全部数据类型可用的:

数据类型 存储分配 值范围
Boolean 取决于实施平台
Byte 1个字节 0到255(无符号)
Char 2个字节 0〜65535(无符号)
Date 8个字节 00:00:00(午夜),时间为0001年12月31日11时31分至晚上11:59:59
Decimal 16字节 0至+/- 79,228,162,514,264,337,593,543,950,335(+/- 7.9 ... E + 28),没有小数点; 0到+/- 7.9228162514264337593543950335,其中小数点右边有28个位
Double 8个字节

 

-1.79769313486231570E + 308至-4.94065645841246544E-324,对于负值

4.94065645841246544E-324至1.79769313486231570E + 308,对于正值

 

Integer 4个字节 -2,147,483,648至2,147,483,647(有符号)
Long 8个字节 -9,223,372,036,854,775,808至9,223,372,036,854,775,807(签字)
Object

在32位平台上的4个字节

在64位平台8字节

任何类型均可以存储在Object类型的变量中
SByte 1个字节 -128至127(签字)
Short 2个字节 -32,768至32,767(签字)
Single 4个字节

-3.4028235E + 38至-1.401298E-45为负值;

1.401298E-45至3.4028235E + 38正值

String 取决于实施平台 0到大约20亿个Unicode字符
UInteger 4个字节 0至4294967295(无符号)
ULONG 8个字节 0至18,446,744,073,709,551,615(签名)
User-Defined 取决于实施平台 结构的每一个成员具备由其数据类型肯定的范围而且独立于其余成员的范围
UShort 2个字节 0至65,535(无符号)

 

示例

下面的示例演示使用的一些类型︰

Module DataTypes
   Sub Main()
      Dim b As Byte
      Dim n As Integer
      Dim si As Single
      Dim d As Double
      Dim da As Date
      Dim c As Char
      Dim s As String
      Dim bl As Boolean
      b = 1
      n = 1234567
      si = 0.12345678901234566
      d = 0.12345678901234566
      da = Today
      c = "U"c
      s = "Me"
      If ScriptEngine = "VB" Then
         bl = True
      Else
         bl = False
      End If
      If bl Then
         'the oath taking
          Console.Write(c & " and," & s & vbCrLf)
          Console.WriteLine("declaring on the day of: {0}", da)
          Console.WriteLine("We will learn VB.Net seriously")
          Console.WriteLine("Lets see what happens to the floating point variables:")
          Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
      End If
      Console.ReadKey()
   End Sub

End Module

 

当上述代码被编译和执行时,它产生了如下结果:

U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously
Lets see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346

 

VB.Net中的类型转换函数

VB.Net提供如下内联类型转换函数:

SN 功能和说明
1

CBool(表达式)

将表达式转换为布尔数据类型。

2

CByte(表达式)

将表达式转换为字节数据类型。

3

CChar(表达式)

将表达式转换为Char数据类型。

4

CDate(表达式)

将表达式转换为Date数据类型

5

CDbl(表达式)

将表达式转换为双精度数据类型。

6

CDec(表达式)

将表达式转换为十进制数据类型。

7

CInT(表达式)

将表达式转换为整数数据类型。

8

CLng函数(表达式)

将表达式转换为长数据类型。

9

CObj(表达式)

将表达式转换为对象类型。

10

CSByte(表达式)

将表达式转换为SByte数据类型。

11

CShort(表达式)

将表达式转换为短数据类型。

12

CSng函数(表达式)

将表达式转换为单一数据类型。

13

CStr的(表达式)

将表达式转换为字符串数据类型。

14

CUInt(表达式)

将表达式转换为UInt数据类型。

15

CULng(表达式)

将表达式转换为ULng数据类型。

16

CUShort(表达式)

将表达式转换为UShort数据类型。

 

示例:

下面的例子演示了其中的一些功能:

Module DataTypes
   Sub Main()
      Dim n As Integer
      Dim da As Date
      Dim bl As Boolean = True
      n = 1234567
      da = Today
      Console.WriteLine(bl)
      Console.WriteLine(CSByte(bl))
      Console.WriteLine(CStr(bl))
      Console.WriteLine(CStr(da))
      Console.WriteLine(CChar(CChar(CStr(n))))
      Console.WriteLine(CChar(CStr(da)))
      Console.ReadKey()
   End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果:

True
-1
True
12/4/2012
1
1

 

 

VB.Net - 变量

 

 

一个变量只是一个给咱们的程序能够操做的存储区域的名字。 VB.Net中的每一个变量都有一个特定的类型,它决定了变量内存的大小和布局; 能够存储在该存储器内的值的范围; 以及能够应用于该变量的一组操做。

咱们已经讨论了各类数据类型。 VB.Net中提供的基本值类型能够分为:

 

 

类型 示例
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char
Floating point types Single and Double
Decimal types Decimal
Boolean types True or False values, as assigned
Date types Date

VB.Net还容许定义其余值类型的变量,如枚举和类的变量的引用类型。 咱们将在后续章节讨论日期类型和类。

 


VB.Net中的变量声明

 

Dim语句用于一个或多个变量的变量声明和存储分配。 Dim语句用于模块,类,结构,过程或块级别。

VB.Net中变量声明的语法是:

 

[ < attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]
[ ReadOnly ] Dim [ WithEvents ] variablelist

一、attributelist是适用于变量的属性列表。 可选的。
 

二、accessmodifier定义变量的访问级别,它具备值 - Public,Protected,Friend,Protected Friend和Private。 可选的。


三、Shared共享声明一个共享变量,它不与类或结构的任何特定实例相关联,而是可用于类或结构的全部实例。 可选的。

四、Shadows阴影表示变量在基类中从新声明和隐藏一个同名的元素或一组重载的元素。 可选的。

五、Static表示变量将保留其值,即便在声明它的过程终止以后。 可选的。
 

六、ReadOnly表示变量能够读取,但不能写入。 可选的。
 

七、WithEvents指定该变量用于响应分配给变量的实例引起的事件。 可选的。
 

八、Variablelist提供了声明的变量列表。

 

变量列表中的每一个变量具备如下语法和部分:

variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]

一、variablename:是变量的名称
 

二、boundslist:可选。 它提供了数组变量的每一个维度的边界列表。
 

三、New:可选。 当Dim语句运行时,它建立一个类的新实例。

四、datatype:若是Option Strict为On,则为必需。 它指定变量的数据类型。
 

五、initializer:若是未指定New,则为可选。 建立时评估并分配给变量的表达式。

 

一些有效的变量声明及其定义以下所示:

Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

 

VB.Net中的变量初始化

变量被初始化(赋值)一个等号,而后是一个常量表达式。 初始化的通常形式是:

variable_name = value;

 

例如,

Dim pi As Double
pi = 3.14159

 

您能够在声明时初始化变量,以下所示:

Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"

 

示例

尝试下面的例子,它使用各类类型的变量:

Module variablesNdataypes
   Sub Main()
      Dim a As Short
      Dim b As Integer
      Dim c As Double
      a = 10
      b = 20
      c = a + b
      Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
      Console.ReadLine()
   End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果:

a = 10, b = 20, c = 30

 

接受来自用户的值

System命名空间中的控制台类提供了一个函数ReadLine,用于接受来自用户的输入并将其存储到变量中。 例如,

Dim message As String
message = Console.ReadLine

 

下面的例子说明:

Module variablesNdataypes
   Sub Main()
      Dim message As String
      Console.Write("Enter message: ")
      message = Console.ReadLine
      Console.WriteLine()
      Console.WriteLine("Your Message: {0}", message)
      Console.ReadLine()
   End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果(假设用户输入的Hello World):

Enter message: Hello World   
Your Message: Hello World

 

Lvalues和Rvalues

有两种表达式:

  • lvalue:做为左值的表达式可能出如今赋值的左侧或右侧。
  • rvalue:做为右值的表达式可能出如今做业的右侧但不是左侧。

 

变量是左值,所以可能出如今做业的左侧。 数字文字是右值,所以可能不会分配,不能出如今左侧。 如下是有效的语句:

Dim g As Integer = 20

 

但如下并非有效的语句,并会生成编译时的错误:

20 = g

 

 

VB.Net - 常数和枚举

 

 

constants 常数指的是程序在执行过程当中可能不会改变的固定值。 这些固定值也称为文字。

常量能够是任何基本数据类型,如整数常量,浮点常量,字符常量或字符串常量。 还有枚举常量。

常量被视为常规变量,除了它们的值不能在它们的定义以后被修改。
 

enumeration 枚举是一组命名的整数常量。

 

 

声明常量

 

在VB.Net中,常量是使用Const语句声明的。 Const语句用于模块,类,结构,过程或块级别,以用于替换文字值。

Const语句的语法是:

 

[ < attributelist> ] [ accessmodifier ] [ Shadows ] 
Const constantlist

一、attributelist:指定应用于常量的属性列表; 您能够提供多个属性,以逗号分隔。 可选的。
 

二、accessmodifier:指定哪些代码能够访问这些常量。 可选的。 值能够是:Public, Protected, Friend, Protected Friend, or Private.

三、Shadows:这使常量隐藏基类中相同名称的编程元素。 可选的。

四、Constantlist:给出声明的常量的名称列表。 必填。

 

其中,每一个常量名都有如下语法和部分:

constantname [ As datatype ] = initializer

一、constantname 常量名:指定常量的名称


二、data type 数据类型:指定常量的数据类型


三、initializer 初始值设定:指定分配给常量的值

 

例如,

'The following statements declare constants.'
Const maxval As Long = 4999
Public Const message As String = "HELLO" 
Private Const piValue As Double = 3.1415

 

示例

如下示例演示了常量值的声明和使用:

Module constantsNenum
   Sub Main()
      Const PI = 3.14149
      Dim radius, area As Single
      radius = 7
      area = PI * radius * radius
      Console.WriteLine("Area = " & Str(area))
      Console.ReadKey()
   End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果:

Area = 153.933

 

在VB.Net中输出和显示常量

VB.Net提供如下打印和显示常量:

Constant 描述
vbCrLf 回车/换行字符组合。
vbCr 回车字符。
vbLf 换行字符。
vbNewLine 换行字符。
vbNullChar 空字符。
vbNullString 不等于零长度字符串(“”); 用于调用外部过程。
vbObjectError 错误号。用户定义的错误号应大于此值。例如: 
Err.Raise(数字)= vbObjectError + 1000
vbTab 标签字符。
vbBack 退格字符。

 

声明枚举

 

使用Enum语句声明枚举类型。 Enum语句声明一个枚举并定义其成员的值。 Enum语句能够在模块,类,结构,过程或块级别使用。

Enum语句的语法以下:

 

[ < attributelist > ] [ accessmodifier ]  [ Shadows ] 
Enum enumerationname [ As datatype ] 
   memberlist
End Enum

一、attributelist:指应用于变量的属性列表。 可选的。
 

二、asscessmodifier:指定哪些代码能够访问这些枚举。 可选的。 值能够是:公共,受保护,朋友或私人。

三、Shadows:这使枚举隐藏基类中相同名称的编程元素。 可选的。

四、enumerationname:枚举的名称。 必填

五、datatype:指定枚举的数据类型及其全部成员。
 

六、memberlist:指定在此语句中声明的成员常数的列表。 必填。

 

成员列表中的每一个成员具备如下语法和部分:

[< attribute list>] member name [ = initializer ]
  • name 名称 :指定成员的名称。必填。

  • initializer 初始化 :分配给枚举成员的值。可选的。

 

例如,

Enum Colors
   red = 1
   orange = 2
   yellow = 3
   green = 4
   azure = 5
   blue = 6
   violet = 7
End Enum

 

示例

如下示例演示了Enum变量颜色的声明和使用:

Module constantsNenum
   Enum Colors
      red = 1
      orange = 2
      yellow = 3
      green = 4
      azure = 5
      blue = 6
      violet = 7
   End Enum
   Sub Main()
      Console.WriteLine("The Color Red is : " & Colors.red)
      Console.WriteLine("The Color Yellow is : " & Colors.yellow)
      Console.WriteLine("The Color Blue is : " & Colors.blue)
      Console.WriteLine("The Color Green is : " & Colors.green)
      Console.ReadKey()
   End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果:

The Color Red is: 1
The Color Yellow is: 3
The Color Blue is: 6
The Color Green is: 4

 

 

 

 

VB.Net - 修饰符

 

 

 

修饰符是经过任何编程元素添加的关键字,以便特别强调编程元素将如何在程序中执行或将被访问

例如,访问修饰符:Public, Private, Protected, Friend, Protected Friend等,指示编程元素的访问级别,如变量,常量,枚举或类。

 

 

VB.Net中可用的修饰符列表

下表提供了VB.Net修饰符的完整列表:

S.N 修饰符 描述
1 Ansi 指定Visual Basic应该将全部字符串编组到美国国家标准协会(ANSI)值,而不考虑正在声明的外部过程的名称。
2 Assembly 指定源文件开头的属性适用于整个程序集。
3 Async 表示它修改的方法或lambda表达式是异步的。 这样的方法被称为异步方法。 异步方法的调用者能够恢复其工做,而没必要等待异步方法完成。
4 Auto 在外部过程的调用期间,十进制中的chchetetmodifierpart提供用于编组字符串的字符集信息。 它还会影响Visual Basic如何在外部文件中搜索外部过程名称。 Auto修饰符指定Visual Basic应根据.NET Framework规则编组字符串。
5 ByRef 指定参数经过引用传递,即被调用过程能够更改调用代码中参数下面的变量的值。 它在下列语境下使用:
  • 声明声明
  • 函数语句
  • Sub语句
6 BYVAL 指定传递参数时,调用过程或属性不能更改调用代码中参数下面的变量的值。 它在下列语境下使用:
  • 声明语句
  • 函数语句
  • 运算符的声明
  • 属性声明
  • Sub语句
7 Default 标识属性做为它的类、 结构或接口的默认属性。
8 Friend

 

指定一个或多个声明的编程元素能够从包含其声明的程序集中访问,而不只仅是声明它们的组件。

Friendaccess一般是应用程序编程元素的首选级别,Friend是接口,模块,类或结构的默认访问级别。

 

9 In 它用于通用接口和代理。
10 Iterator 指定函数或Get访问器是迭代器。 Aniterator对集合执行自定义迭代。
11 Key Key关键字使您可以为匿名类型的属性指定行为。
12 Module 指定源文件开头的属性适用于当前装配模块。 它与Module语句不一样。
13 MustInherit 指定一个类只能用来做为基类,而且你不能直接建立一个对象。
14 MustOverride 指定属性或过程未在此类中实现,必须在导出类中重写,而后才能使用。
15 Narrowing 表示转换运算符(CType)将类或结构转换为可能不能保存原始类或结构的某些可能值的类型。
16 NotInheritable 指定类不能用做基类。
17 NotOverridable 指定不能在派生类中重写属性或过程。
18 Optional 指定当程序被调用的过程参数能够被省略。
19 Out 对于通用类型参数,Out关键字指定类型是协变的。
20 Overloads 指定属性或过程从新声明具备相同名称的一个或多个现有属性或过程。
21 Overridable 指定属性或过程能够由派生类中具备相同名称的属性或过程覆盖。
22 Overrides 指定属性或过程覆盖从基类继承的命名相同的属性或过程。
23 ParamArray

ParamArray容许您将任意数量的参数传递给过程。

ParamArray参数始终使用ByVal声明。

24 Partial 表示类或结构声明是类或结构的部分定义。
25 Private 指定一个或多个声明的编程元素只能在其声明上下文中访问,包括来自任何包含的类型。
26 Protected 指定一个或多个声明的编程元素只能从其本身的类或派生类中访问。
27 Public 指定一个或多个声明的编程元素没有访问限制。
28 ReadOnly 指定能够读取但不写入变量或属性。
29 Shadows 指定声明的编程元素在基类中从新声明和隐藏相同命名的元素或一组重载的元素。
30 Shared 指定一个或多个声明的编程元素与类或结构(而不是类或结构的特定实例)关联。
31 Static 指定一个或多个已声明的局部变量将继续存在,并在声明它们的过程终止后保留其最新值。
32 Unicode 指定Visual Basic应将全部字符串编组为Unicode值,而不考虑正在声明的外部过程的名称。
33 Widening 表示转换运算符(CType)将类或结构转换为能够保存原始类或结构的全部可能值的类型。
34 WithEvents 指定一个或多个声明的成员变量引用能够引起事件的类的实例。
35 WriteOnly 指定能够写入但不读取属性。

 

 

VB.Net - 声明

 

 

statement 声明是Visual Basic程序中的完整指令。 它能够包含关键字,运算符,变量,字面值,常量和表达式。

语句能够分类为:

一、Declaration statements 声明语句 - 这些语句是您命名变量,常量或过程的语句,也能够指定数据类型。

 

二、Executable statements 可执行语句 - 这些是启动动做的语句。 这些语句能够调用方法或函数,经过代码块循环或分支,或者将值或表达式赋值给变量或常量。 在最后一种状况下,它被称为Assignment语句。

声明语句

 

声明语句用于命名和定义过程、 变量、 属性、 数组和常量。当你声明的编程元素时,您还能够定义其数据类型、 访问级别和范围。

 

您能够声明的编程元素包括变量、 常数、 枚举、 类、 结构、模块、 接口、 程序、 过程参数、 函数返回值、 外部过程的引用、 运算符、 属性、 事件和委托。

 

如下是在 VB.Net 中的声明语句︰

S.N 声明和说明 示例
1

Dim Statement

Dim语句

Declares and allocates storage space for one or more variables.

声明和分配一个或多个变量的存储空间。

Dim number As Integer
Dim quantity As Integer = 100
Dim message As String = "Hello!"
2 Const Statement 
Const语句

Declares and defines one or more constants.
声明和定义一个或多个常量。
Const maximum As Long = 1000
Const naturalLogBase As Object 
= CDec(2.7182818284)
3 Enum Statement 
枚举语句

Declares an enumeration and defines the values of its members.
声明一个枚举并定义其成员的值。
Enum CoffeeMugSize
    Jumbo
    ExtraLarge
    Large
    Medium
    Small
End Enum
4

Class Statement

类语句

Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class comprises.

声明类的名称,并引入该类包含的变量,属性,事件和过程的定义。

Class Box
Public length As Double
Public breadth As Double   
Public height As Double
End Class
5

Structure Statement

结构声明

Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises.

声明结构的名称,并引入结构所包含的变量,属性,事件和过程的定义。

Structure Box
Public length As Double           
Public breadth As Double   
Public height As Double
End Structure
6

Module Statement

模块语句

Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises.

声明模块的名称,并介绍模块包含的变量,属性,事件和过程的定义。

Public Module myModule
Sub Main()
Dim user As String = 
InputBox("What is your name?") 
MsgBox("User name is" & user)
End Sub 
End Module
7

Interface Statement

接口语句
Declares the name of an interface and introduces the definitions of the members that the interface comprises.
声明接口的名称,并介绍接口包含的成员的定义。

 

Public Interface MyInterface
    Sub doSomething()
End Interface
8

Function Statement

函数语句

Declares the name, parameters, and code that define a Function procedure.

声明定义函数过程的名称,参数和代码。

Function myFunction
(ByVal n As Integer) As Double 
    Return 5.87 * n
End Function
9

Sub Statement

子语句

Declares the name, parameters, and code that define a Sub procedure.

声明定义Sub过程的名称,参数和代码。

Sub mySub(ByVal s As String)
    Return
End Sub
10

Declare Statement

声明语句

Declares a reference to a procedure implemented in an external file.

声明对在外部文件中实现的过程的引用。

Declare Function getUserName
Lib "advapi32.dll" 
Alias "GetUserNameA" 
(
  ByVal lpBuffer As String, 
  ByRef nSize As Integer) As Integer
11

Operator Statement

运算符声明

Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.

声明的运算符符号、 操做数和在类或结构定义一个运算符过程的代码。

Public Shared Operator +
(ByVal x As obj, ByVal y As obj) As obj
        Dim r As New obj
' implemention code for r = x + y
        Return r
    End Operator
12

Property Statement

属性声明

Declares the name of a property, and the property procedures used to store and retrieve the value of the property.

声明属性的名称,以及用于存储和检索属性值的属性过程。

ReadOnly Property quote() As String 
    Get 
        Return quoteString
    End Get 
End Property
13

Event Statement

事件声明

Declares a user-defined event.

声明用户定义的事件。

Public Event Finished()
14

Delegate Statement

委托声明

Used to declare a delegate.

用于声明一个委托。

Delegate Function MathOperator( 
    ByVal x As Double, 
    ByVal y As Double 
) As Double

 

可执行语句

 

可执行语句执行操做。 调用过程,分支到代码中的另外一个地方,循环使用几个语句或评估表达式的语句是可执行语句。 赋值语句是可执行语句的一种特殊状况。

 

如下示例演示了一个决策语句:

Module decisions
   Sub Main()
      'local variable definition '
      Dim a As Integer = 10

      ' check the boolean condition using if statement '
      If (a < 20) Then
         ' if condition is true then print the following '
         Console.WriteLine("a is less than 20")
      End If
      Console.WriteLine("value of a is : {0}", a)
      Console.ReadLine()
   End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果:

a is less than 20;
value of a is : 10

 

 

 

VB.Net - 指令

 

 

VB.Net编译器指令给编译器指令,以便在实际编译开始以前预处理信息。

全部这些指令以#开头,而且在一行上的指令以前只能出现空格字符。 这些指令不是语句。
 

VB.Net编译器没有单独的预处理器; 然而,指令被处理,就像有一个。 在VB.Net中,编译器指令用于帮助条件编译。 与C和C ++指令不一样,它们不用于建立宏。

 

 

在 VB.Net 中的编译器指令

VB.Net提供了如下一组编译器指令:

 

  • The #Const 指令

  • The #ExternalSource 指令

  • The #If...Then...#Else 指令

  • The #Region 指令

 

 

The#Const指令

该指令定义条件编译常量。语法这个指令是:

#Const constname = expression

 

  • constname:指定常量的名称。必要。

  • expression :它是文字或其余条件编译器常量,或包含任何或全部算术或逻辑运算符(除了Is)的组合。

 

例如,

#Const state = "WEST BENGAL"

 

示例

如下代码演示了伪指令的使用:

Module mydirectives
#Const age = True
Sub Main()
   #If age Then
      Console.WriteLine("You are welcome to the Robotics Club")
   #End If
   Console.ReadKey()
End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果:

You are welcome to the Robotics Club

 

The#ExternalSource指令

 

此指令用来指示特定行的源代码和源的外部文本之间的映射。它使用仅由编译器和调试器并不影响代码编译。

 

此指令容许包括从外部代码文件外部的代码到一个源代码文件。

 

此指令的语法是︰

 

#ExternalSource( StringLiteral , IntLiteral )
    [ LogicalLine ]
#End ExternalSource

#ExternalSource伪指令的参数是外部文件的路径,第一行的行号和发生错误的行。

 

示例

 

如下代码演示了伪指令的使用:

Module mydirectives
    Public Class ExternalSourceTester

        Sub TestExternalSource()

        #ExternalSource("c:vbprogsdirectives.vb", 5)
            Console.WriteLine("This is External Code. ")
        #End ExternalSource

        End Sub
    End Class

    Sub Main()
        Dim t As New ExternalSourceTester()
        t.TestExternalSource()
        Console.WriteLine("In Main.")
        Console.ReadKey()

    End Sub

 

当上述代码被编译和执行时,它产生了如下结果:

This is External Code.
In Main.

 

 

The #If...Then...#Else 指令

 

此伪指令有条件地编译所选的Visual Basic代码块。

此伪指令的语法是:

 

#If expression Then
   statements
[ #ElseIf expression Then
   [ statements ]
...
#ElseIf expression Then
   [ statements ] ]
[ #Else
   [ statements ] ]
#End If

 

例如,

#Const TargetOS = "Linux"
#If TargetOS = "Windows 7" Then
   ' Windows 7 specific code
#ElseIf TargetOS = "WinXP" Then
   ' Windows XP specific code
#Else
   ' Code for other OS
#End if

 

示例

下面的代码演示一个假设使用的指令:

Module mydirectives
#Const classCode = 8

   Sub Main()
   #If classCode = 7 Then
        Console.WriteLine("Exam Questions for Class VII")
   #ElseIf classCode = 8 Then
        Console.WriteLine("Exam Questions for Class VIII")
   #Else
        Console.WriteLine("Exam Questions for Higher Classes")
   #End If
        Console.ReadKey()

    End Sub
End Module

 

当上述代码被编译和执行时,它产生了如下结果:

Exam Questions for Class VIII

 

 

The #Region指令

 

此伪指令有助于在Visual Basic文件中折叠和隐藏代码段。

此伪指令的语法是:

 

#Region "identifier_string" 
#End Region

 

例如,

#Region "StatsFunctions" 
    ' Insert code for the Statistical functions here.
#End Region

 

 

 

 

VB.Net - 运算符

 

运算符是一个符号,通知编译器执行特定的数学或逻辑操做。 VB.Net丰富的内置运算符,并提供如下类型的经常使用运算符:

  • 算术运算符

  • 比较运算符

  • 逻辑/位运算符

  • 位移位运算符

  • 赋值运算符

  • 其余运算符

 

本教程将介绍最经常使用的运算符。

 

算术运算符

下表显示了VB.Net支持的全部算术运算符。 假设变量A保持2,变量B保持7,则:

 

运算符 描述
^

Raises one operand to the power of anothe

将一个操做数提高为另外一个的权力

B^A will give 49
+

Adds two operand

添加两个操做数s

A + B will give 9
- Subtracts second operand from the first
从第一个操做数中减去第二个操做数
A - B will give -5
*

Multiplies both operands

将两个操做数相乘

A * B will give 14
/ Divides one operand by another and returns a floating point result
将一个操做数除以另外一个操做数,并返回一个浮点结果
B / A will give 3.5
\ Divides one operand by another and returns an integer result
将一个操做数除以另外一个操做数,并返回一个整数结果
B \ A will give 3
MOD Modulus Operator and remainder of after an integer division
模数运算符和整数除法后的余数
B MOD A will give 1

 

比较运算符

下表显示了VB.Net支持的全部比较运算符。 假设变量A保持10,变量B保持20,则:

 

运算符 描述
= Checks if the values of two operands are equal or not; if yes, then condition becomes true.
检查两个操做数的值是否相等; 若是是,则条件变为真。
(A = B)是不正确的。

<>

Checks if the values of two operands are equal or not; if values are not equal, then condition becomes true.

检查两个操做数的值是否相等; 若是值不相等,则条件为真。

(AB)为真。
> Checks if the value of left operand is greater than the value of right operand; if yes, then condition becomes true.
检查左操做数的值是否大于右操做数的值; 若是是,则条件变为真。
(A> B)是不正确的。
< Checks if the value of left operand is less than the value of right operand; if yes, then condition becomes true.
检查左操做数的值是否小于右操做数的值; 若是是,则条件变为真。
(A <B)为真。
> = Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then condition becomes true.
检查左操做数的值是否大于或等于右操做数的值; 若是是,则条件变为真。
(A> = B)是不正确的。
<= Checks if the value of left operand is less than or equal to the value of right operand; if yes, then condition becomes true.
检查左操做数的值是否小于或等于右操做数的值; 若是是,则条件变为真。
(A <= B)为真。

 

除了上述状况外,VB.Net提供了三个比较运算符,咱们将在之后的章节中使用; 然而,咱们在这里给出一个简短的描述。


一、Is运算符 - 它比较两个对象引用变量,并肯定两个对象引用是否引用相同的对象,而不执行值比较。 若是object1和object2都引用彻底相同的对象实例,则result为True; 不然,result为False。

二、IsNot运算符 - 它还比较两个对象引用变量,并肯定两个对象引用是否引用不一样的对象。 若是object1和object2都引用彻底相同的对象实例,则result为False; 不然,result为True。

三、Like运算符 - 它将字符串与模式进行比较。

 

逻辑/位运算符

下表显示了VB.Net支持的全部逻辑运算符。 假设变量A保持布尔值True,变量B保持布尔值False,则:

 

运算符 描述
And It is the logical as well as bitwise AND operator. If both the operands are true, then condition becomes true. This operator does not perform short-circuiting, i.e., it evaluates both the expressions.
它是逻辑以及按位AND运算符。 若是两个操做数都为真,则条件为真。 此运算符不执行短路,即,它评估两个表达式。
(A和B)为假。
Or It is the logical as well as bitwise OR operator. If any of the two operands is true, then condition becomes true. This operator does not perform short-circuiting, i.e., it evaluates both the expressions.
它是逻辑以及按位或运算符。 若是两个操做数中的任何一个为真,则条件为真。 此运算符不执行短路,即,它评估两个表达式。
(A或B)为真。
Not It is the logical as well as bitwise NOT operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.
它是逻辑以及按位非运算符。 用于反转其操做数的逻辑状态。 若是条件为真,则逻辑非运算符将为假。
没有(A和B)为真。
Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns True if both expressions are True or both expressions are False; otherwise it returns False. This operator does not perform short-circuiting, it always evaluates both expressions and there is no short-circuiting counterpart of this operator.
它是逻辑以及按位逻辑异或运算符。 若是两个表达式都为True或两个表达式都为False,则返回True; 不然返回False。 该运算符不会执行短路,它老是评估这两个表达式,而且没有该运算符的短路对应。
异或B为真。
AndAlso It is the logical AND operator. It works only on Boolean data. It performs short-circuiting.
它是逻辑 AND 运算符。它仅适用于布尔型数据。它执行短路。
(A AndAlso运算B)为假。
OrElse It is the logical OR operator. It works only on Boolean data. It performs short-circuiting.
它是逻辑或运算符。 它只适用于布尔数据。 它执行短路。
(A OrElse运算B)为真。
IsFalse It determines whether an expression is False.
它肯定表达式是否为假。
 
IsTrue It determines whether an expression is True.
它肯定表达式是否为真。
 

 

位移运算符

 

咱们已经讨论了按位运算符。 位移运算符对二进制值执行移位操做。 在进入位移运算符以前,让咱们来了解位操做。

按位运算符处理位并执行逐位操做。 &,|和^的真值表以下:

 

p q p&Q p | q p ^ Q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

假设A = 60; 和B = 13; 如今的二进制格式,他们将以下:

 

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A | B = 0011 1101

A ^ B = 0011 0001

〜A = 1100 0011

 

 

咱们已经看到VB.Net支持的Bitwise运算符是And,Or,Xor和Not。 位移位算子分别是用于左移和右移的>>和<<。

假设变量A保持60,变量B保持13,则:

 

 

 

运算符 描述 示例
And Bitwise AND Operator copies a bit to the result if it exists in both operands.
若是两个操做数都存在,则按位AND运算符将一个位复制到结果。
(A AND B) will give 12, which is 0000 1100
Or Binary OR Operator copies a bit if it exists in either operand.
二进制OR运算符复制一个位,若是它存在于任一操做数。
(A Or B) will give 61, which is 0011 1101
Xor Binary XOR Operator copies the bit if it is set in one operand but not both.
二进制XOR运算符复制该位,若是它在一个操做数中设置,但不是两个操做数。
(A Xor B) will give 49, which is 0011 0001
Not Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
二进制补码运算符是一元的,具备“翻转”位的效果。
(Not A ) will give -61, which is 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
二进制左移位运算符。 左操做数值向左移动由右操做数指定的位数。
A << 2 will give 240, which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
二进制右移运算符。 左操做数值向右移动由右操做数指定的位数。
A >> 2 will give 15, which is 0000 1111

 

赋值运算符

VB.Net支持如下赋值运算符:

 

运算符 描述
=

Simple assignment operator, Assigns values from right side operands to left side operand

简单赋值操做符,将值从右侧操做数分配给左侧操做数

C = A + B A + B将赋值为C
+ = Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand
添加AND赋值运算符,向左操做数添加右操做数,并将结果赋值给左操做数
C + = A等于C = C + A
- = Subtract AND assignment operator, It subtracts right operand from the left operand and assigns the result to left operand
减法AND赋值运算符,它从左操做数中减去右操做数,并将结果赋值给左操做数
Ç - = A等于C = C - 一个
* = Multiply AND assignment operator, It multiplies right operand with the left operand and assigns the result to left operand
乘法AND赋值运算符,它将右操做数与左操做数相乘,并将结果赋值给左操做数
C * = A等于C = C * A
/ = Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand (floating point division)
除法AND赋值运算符,它用右操做数划分左操做数,并将结果分配给左操做数(浮点除法)
C / = A等于C = C / A
\ = Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand (Integer division)
除法AND赋值运算符,它用右操做数划分左操做数,并将结果分配给左操做数(整数除法)
ç = A等于C = C A
^ = Exponentiation and assignment operator. It raises the left operand to the power of the right operand and assigns the result to left operand.
指数和赋值运算符。 它将左操做数提高为右操做数的幂,并将结果分配给左操做数。
C ^ = A等于C = C ^ A
<< = Left shift AND assignment operator
左移AND赋值运算符
C语言的<< = 2是同C = C << 2
>> = Right shift AND assignment operator
右移AND赋值运算符
C >> = 2 >> 2同C = C
&= Concatenates a String expression to a String variable or property and assigns the result to the variable or property.
将String表达式链接到String变量或属性,并将结果分配给变量或属性。

STR1&= STR2赛车是同样的

STR1 = STR1与STR2

 

其余运算符

有不多其余重要的操做系统支持VB.Net。

 

运算符 描述
AddressOf Returns the address of a procedure.
返回过程的地址。
AddHandler Button1.Click,
AddressOf Button1_Click
Await It is applied to an operand in an asynchronous method or lambda expression to suspend execution of the method until the awaited task completes.
它应用于异步方法或lambda表达式中的操做数,以暂停该方法的执行,直到等待的任务完成。
Dim result As res
= Await AsyncMethodThatReturnsResult()
Await AsyncMethod()
GetType It returns a Type object for the specified type. The Type object provides information about the type such as its properties, methods, and events.
它返回指定类型的Type对象。 Type对象提供有关类型的信息,例如其属性,方法和事件。
MsgBox(GetType(Integer).ToString())
Function Expression It declares the parameters and code that define a function lambda expression.
它声明定义函数lambda表达式的参数和代码。
Dim add5 = Function(num As
 Integer) num + 5
'prints 10
Console.WriteLine(add5(5))
If It uses short-circuit evaluation to conditionally return one of two values. The If operator can be called with three arguments or with two arguments.
它使用短路评估有条件地返回两个值之一。 可使用三个参数或两个参数调用If运算符。
Dim num = 5
Console.WriteLine(If(num >= 0,
"Positive", "Negative"))

 

VB.Net中的运算符优先级

运算符优先级肯定表达式中的术语分组。 这会影响表达式的计算方式。 某些运算符比其余运算符具备更高的优先级; 例如,乘法运算符的优先级高于加法运算符:

例如,x = 7 + 3 * 2; 这里,x被分配13,而不是20,由于operator *具备比+高的优先级,因此它首先乘以3 * 2,而后加到7。

这里,具备最高优先级的运算符出如今表的顶部,具备最低优先级的运算符出如今底部。 在表达式中,将首先计算较高优先级运算符。

 

 

运算符 优先级
Await 最高
Exponentiation (^)  
Unary identity and negation (+, -)  
Multiplication and floating-point division (*, /)  
Integer division (\)  
Modulus arithmetic (Mod)  
Addition and subtraction (+, -)  
Arithmetic bit shift (<<, >>)  
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)  
Negation (Not)  
Conjunction (And, AndAlso)  
Inclusive disjunction (Or, OrElse)  
Exclusive disjunction (Xor) 最低

 

 

 

VB.Net - 决策

 

 

决策结构须要程序员指定一个或多个条件进行评估或测试程序和语句或语句的执行,若是肯定的条件为真,并选择,若是肯定的条件为假,则执行其它语句。

 

如下是决策的典型结构发如今大多数编程语言的通常形式︰

 

 

决策声明中VB.Net

 

VB.Net提供如下类型的决策语句。 单击如下连接以检查其详细信息。

声明 描述

If ... Then statement

An If...Then statement consists of a boolean expression followed by one or more statements.
一个If...Then语句由一个布尔表达式后跟一个或多个语句组成。

If...Then...Else statement

An If...Then statement can be followed by an optional Else statement, which executes when the boolean expression is false.
一个If...Then语句后面能够是一个可选的Else语句 ,当布尔表达式为假时执行。

nested If statements

You can use one If or Else if statement inside another If or Else if statement(s).
您能够在一个ifelse if语句中使用If或Else if语句。

Select Case statement

You can use one If or Else if statement inside another If or Else if statement(s).
Select Case语句容许根据值列表测试变量的相等性。

nested Select Case statements

You can use one select case statement inside another select case statement(s).
您可使用一个select case语句中使用一个 select case语句。

 

 

 

VB.Net - 循环

 

 

可能有一种状况,当你须要执行一段代码几回。 通常来讲,语句是按顺序执行的:函数中的第一个语句首先执行,而后是第二个语句,依此类推。

编程语言提供容许更复杂的执行路径的各类控制结构。
 

循环语句容许咱们屡次执行一个语句或一组语句,如下是大多数编程语言中循环语句的通常形式:

 

 

环路结构

 

VB.Net提供如下类型的循环来处理循环需求。 单击如下连接以检查其详细信息。

 

循环类型 描述

Do Loop

It repeats the enclosed block of statements while a Boolean condition is True or until the condition becomes True. It could be terminated at any time with the Exit Do statement.
它重复包含的语句块内布尔条件为True或直到条件变为True。 它能够随时使用Exit Do语句终止。

For...Next

It repeats a group of statements a specified number of times and a loop index counts the number of loop iterations as the loop executes.
它重复指定次数的一组语句,循环索引计算循环执行时的循环迭代数。

For Each...Next

It repeats a group of statements for each element in a collection. This loop is used for accessing and manipulating all elements in an array or a VB.Net collection.
它为集合中的每一个元素重复一组语句。 这个循环用于访问和操做数组或VB.Net集合中的全部元素。

While... End While

It executes a series of statements as long as a given condition is True.
只要给定条件为True,它就执行一系列语句。

With... End With

It is not exactly a looping construct. It executes a series of statements that repeatedly refer to a single object or structure.
它不是一个循环结构。 它执行一系列重复引用单个对象或结构的语句。

Nested loops

You can use one or more loops inside any another While, For or Do loop.
您能够在任何其余While,For或Do循环中使用一个或多个循环。

 

 

循环控制语句:

 

循环控制语句从其正常序列改变执行。 当执行离开做用域时,在该做用域中建立的全部自动对象都将被销毁。

VB.Net提供如下控制语句。 单击如下连接以检查其详细信息。

 

控制语句 描述

Exit statement

Terminates the loop or select case statement and transfers execution to the statement immediately following the loop or select case.

Continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.致使循环跳过其自己的其他部分,并在重复以前当即从新测试其状态。

GoTo statement

Transfers control to the labeled statement. Though it is not advised to use GoTo statement in your program.

将控制转移到带标签的语句。 虽然不建议在程序中使用GoTo语句。

 

 

 

 

 

未完待续,下一章节,つづく