VB C# 语法对比图 (代码实例)

Comments

VB.NET

'Single line onlyRem Single line only

C#

// Single line/* Multipleline *//// XML comments on single line/** XML comments on multiple lines */

Data Types

VB.NET

'Value TypesBooleanByteChar (example: "A")Short, Integer, LongSingle, DoubleDecimalDate'Reference TypesObjectStringDim x As IntegerSystem.Console.WriteLine(x.GetType())System.Console.WriteLine(TypeName(x))'Type conversionDim d As Single = 3.5Dim i As Integer = CType (d, Integer)i = CInt (d)i = Int(d)

C#

//Value Typesboolbyte, sbytechar (example: 'A')short, ushort, int, uint, long, ulongfloat, doubledecimalDateTime//Reference Typesobjectstringint x;Console.WriteLine(x.GetType())Console.WriteLine(typeof(int))//Type conversionfloat d = 3.5;int i = (int) d

Constants

VB.NET

Const MAX_AUTHORS As Integer = 25ReadOnly MIN_RANK As Single = 5.00

C#

const int MAX_AUTHORS = 25;readonly float MIN_RANKING = 5.00;

Enumerations

VB.NET

Enum ActionStart'Stop is a reserved word[Stop]RewindForwardEnd EnumEnum StatusFlunk = 50Pass = 70Excel = 90End EnumDim a As Action = Action.StopIf a <> Action.Start Then _'Prints "Stop is 1"System.Console.WriteLine(a.ToString & " is " & a)'Prints 70System.Console.WriteLine(Status.Pass)'Prints PassSystem.Console.WriteLine(Status.Pass.ToString())

C#

enum Action {Start, Stop, Rewind, Forward};enum Status {Flunk = 50, Pass = 70, Excel = 90};Action a = Action.Stop;if (a != Action.Start)//Prints "Stop is 1"System.Console.WriteLine(a + " is " + (int) a);// Prints 70System.Console.WriteLine((int) Status.Pass);// Prints PassSystem.Console.WriteLine(Status.Pass);

Operators

VB.NET

'Comparison=  <  >  <=  >=  <>'Arithmetic+  -  *  /Mod(integer division)^  (raise to a power)'Assignment=  +=  -=  *=  /=  =  ^=  <<=  >>=  &='BitwiseAnd  AndAlso  Or  OrElse  Not  <<  >>'LogicalAnd  AndAlso  Or  OrElse  Not'String Concatenation& 

C#

//Comparison==  <  >  <=  >=  !=//Arithmetic+  -  *  /%  (mod)/  (integer division if both operands are ints)Math.Pow(x, y)//Assignment=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --//Bitwise&  |  ^   ~  <<  >>//Logical&&  ||   !//String Concatenation+

Choices

VB.NET

greeting = IIf(age < 20, "What's up?", "Hello")'One line doesn't require "End If", no "Else"If language = "VB.NET" Then langType = "verbose"'Use: to put two commands on same lineIf x <> 100 And y < 5 Then x *= 5 : y *= 2  'PreferredIf x <> 100 And y < 5 Thenx *= 5y *= 2End If'or to break up any long single command use _If henYouHaveAReally < longLine And _itNeedsToBeBrokenInto2   > Lines  Then _UseTheUnderscore(charToBreakItUp)If x > 5 Thenx *= yElseIf x = 5 Thenx += yElseIf x < 10 Thenx -= yElsex /= yEnd If'Must be a primitive data typeSelect Case color   Case "black", "red"r += 1Case "blue"b += 1Case "green"g += 1Case Elseother += 1End Select

C#

greeting = age < 20 ? "What's up?" : "Hello";if (x != 100 && y < 5){// Multiple statements must be enclosed in {}x *= 5;y *= 2;}if (x > 5)x *= y;else if (x == 5)x += y;else if (x < 10)x -= y;elsex /= y;//Must be integer or stringswitch (color){case "black":case "red":    r++;break;case "blue"break;case "green": g++;  break;default:    other++;break;}

Loops

VB.NET

'Pre-test Loops:While c < 10c += 1End While Do Until c = 10c += 1Loop'Post-test Loop:Do While c < 10c += 1LoopFor c = 2 To 10 Step 2System.Console.WriteLine(c)Next'Array or collection loopingDim names As String() = {"Steven", "SuOk", "Sarah"}For Each s As String In namesSystem.Console.WriteLine(s)Next

C#

//Pre-test Loops: while (i < 10)i++;for (i = 2; i < = 10; i += 2)System.Console.WriteLine(i);//Post-test Loop:doi++;while (i < 10);// Array or collection loopingstring[] names = {"Steven", "SuOk", "Sarah"};foreach (string s in names)System.Console.WriteLine(s);

Arrays

VB.NET

Dim nums() As Integer = {1, 2, 3}For i As Integer = 0 To nums.Length - 1Console.WriteLine(nums(i))Next'4 is the index of the last element, so it holds 5 elementsDim names(4) As Stringnames(0) = "Steven"'Throws System.IndexOutOfRangeExceptionnames(5) = "Sarah"'Resize the array, keeping the existing'values (Preserve is optional)ReDim Preserve names(6)Dim twoD(rows-1, cols-1) As SingletwoD(2, 0) = 4.5Dim jagged()() As Integer = { _New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }jagged(0)(4) = 5

C#

int[] nums = {1, 2, 3};for (int i = 0; i < nums.Length; i++)Console.WriteLine(nums[i]);// 5 is the size of the arraystring[] names = new string[5];names[0] = "Steven";// Throws System.IndexOutOfRangeExceptionnames[5] = "Sarah"// C# can't dynamically resize an array.//Just copy into new array.string[] names2 = new string[7];// or names.CopyTo(names2, 0);Array.Copy(names, names2, names.Length);float[,] twoD = new float[rows, cols];twoD[2,0] = 4.5;int[][] jagged = new int[3][] {new int[5], new int[2], new int[3] };jagged[0][4] = 5;

Functions

VB.NET

'Pass by value (in, default), reference'(in/out), and reference (out)Sub TestFunc(ByVal x As Integer, ByRef y As Integer,ByRef z As Integer)x += 1y += 1z = 5End Sub'c set to zero by defaultDim a = 1, b = 1, c As IntegerTestFunc(a, b, c)System.Console.WriteLine("{0} {1} {2}", a, b, c) '1 2 5'Accept variable number of argumentsFunction Sum(ByVal ParamArray nums As Integer()) As IntegerSum = 0For Each i As Integer In numsSum += iNextEnd Function 'Or use a Return statement like C#Dim total As Integer = Sum(4, 3, 2, 1) 'returns 10'Optional parameters must be listed last'and must have a default valueSub SayHello(ByVal name As String,Optional ByVal prefix As String = "")System.Console.WriteLine("Greetings, " & prefix& " " & name)End SubSayHello("Steven", "Dr.")SayHello("SuOk")

C#

// Pass by value (in, default), reference//(in/out), and reference (out)void TestFunc(int x, ref int y, out int z) {x++;y++;z = 5;}int a = 1, b = 1, c; // c doesn't need initializingTestFunc(a, ref b, out c);System.Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5// Accept variable number of argumentsint Sum(params int[] nums) {int sum = 0;foreach (int i in nums)sum += i;return sum;}int total = Sum(4, 3, 2, 1); // returns 10/* C# doesn't support optional arguments/parameters.Just create two different versions of the same function. */void SayHello(string name, string prefix) {System.Console.WriteLine("Greetings, "     + prefix + " " + name);}void SayHello(string name) {SayHello(name, "");}

Exception Handling

VB.NET

'Deprecated unstructured error handlingOn Error GoTo MyErrorHandler...MyErrorHandler: System.Console.WriteLine(Err.Description)Dim ex As New Exception("Something has really gone wrong.")Throw exTryy = 0x = 10 / yCatch ex As Exception When y = 0 'Argument and When is optionalSystem.Console.WriteLine(ex.Message)FinallyDoSomething()End Try

C#

Exception up = new Exception("Something is really wrong.");throw up; // ha hatry{y = 0;x = 10 / y;}catch (Exception ex) { //Argument is optional, no "When" keywordConsole.WriteLine(ex.Message);}finally{// Do something}

Namespaces

VB.NET

Namespace ASPAlliance.DotNet.Community...End Namespace'orNamespace ASPAllianceNamespace DotNetNamespace Community...End NamespaceEnd NamespaceEnd NamespaceImports ASPAlliance.DotNet.Community

C#

namespace ASPAlliance.DotNet.Community {...}// ornamespace ASPAlliance {namespace DotNet {namespace Community {...}}}using ASPAlliance.DotNet.Community;

Classes / Interfaces

VB.NET

'Accessibility keywordsPublicPrivateFriendProtectedProtected FriendShared'InheritanceClass ArticlesInherits Authors...End Class'Interface definitionInterface IArticle ...End Interface'Extending an interfaceInterface IArticleInherits IAuthor...End Interface'Interface implementation</span>Class PublicationDateImplements</strong> IArticle, IRating...End Class

C#

//Accessibility keywordspublicprivateinternalprotectedprotected internalstatic//Inheritanceclass Articles: Authors {...}//Interface definitioninterface IArticle {...}//Extending an interfaceinterface IArticle: IAuthor {...}//Interface implementationclass PublicationDate: IArticle, IRating {...}

Constructors / Destructors

VB.NET

Class TopAuthorPrivate _topAuthor As IntegerPublic Sub New()_topAuthor = 0End SubPublic Sub New(ByVal topAuthor As Integer)Me._topAuthor = topAuthorEnd SubProtected Overrides Sub Finalize()'Desctructor code to free unmanaged resourcesMyBase.Finalize()End SubEnd Class

C#

class TopAuthor {private int _topAuthor;public TopAuthor() {_topAuthor = 0;}public TopAuthor(int topAuthor) {this._topAuthor= topAuthor}~TopAuthor() {// Destructor code to free unmanaged resources.// Implicitly creates a Finalize method}}

Objects

VB.NET

Dim author As TopAuthor = New TopAuthorWith author.Name = "Steven".AuthorRanking = 3End Withauthor.Rank("Scott")author.Demote() 'Calling Shared method'orTopAuthor.Rank()Dim author2 As TopAuthor = author 'Both refer to same objectauthor2.Name = "Joe"System.Console.WriteLine(author2.Name) 'Prints Joeauthor = Nothing 'Free the objectIf author Is Nothing Then _author = New TopAuthorDim obj As Object = New TopAuthorIf TypeOf obj Is TopAuthor Then _System.Console.WriteLine("Is a TopAuthor object.")

C#

TopAuthor author = new TopAuthor();//No "With" constructauthor.Name = "Steven";author.AuthorRanking = 3;author.Rank("Scott");TopAuthor.Demote() //Calling static methodTopAuthor author2 = author //Both refer to same objectauthor2.Name = "Joe";System.Console.WriteLine(author2.Name) //Prints Joeauthor = null //Free the objectif (author == null)author = new TopAuthor();Object obj = new TopAuthor(); if (obj is TopAuthor)SystConsole.WriteLine("Is a TopAuthor object.");

Structs

VB.NET

Structure AuthorRecordPublic name As StringPublic rank As SinglePublic Sub New(ByVal name As String, ByVal rank As Single)Me.name = nameMe.rank = rankEnd SubEnd StructureDim author As AuthorRecord = New AuthorRecord("Steven", 8.8)Dim author2 As AuthorRecord = authorauthor2.name = "Scott"System.Console.WriteLine(author.name) 'Prints StevenSystem.Console.WriteLine(author2.name) 'Prints Scott

C#

struct AuthorRecord {public string name;public float rank;public AuthorRecord(string name, float rank) {this.name = name;this.rank = rank;}}AuthorRecord author = new AuthorRecord("Steven", 8.8);AuthorRecord author2 = authorauthor.name = "Scott";SystemConsole.WriteLine(author.name); //Prints StevenSystem.Console.WriteLine(author2.name); //Prints Scott

Properties

VB.NET

Private _size As IntegerPublic Property Size() As IntegerGetReturn _sizeEnd GetSet (ByVal Value As Integer)If Value < 0 Then_size = 0Else_size = ValueEnd IfEnd SetEnd Propertyfoo.Size += 1

C#

private int _size;public int Size {get {return _size;}set {if (value < 0)_size = 0;else_size = value;}}foo.Size++;

Delegates / Events

VB.NET

Delegate Sub MsgArrivedEventHandler(ByVal messageAs String)Event MsgArrivedEvent As MsgArrivedEventHandler'or to define an event which declares a'delegate implicitlyEvent MsgArrivedEvent(ByVal message As String)AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback'Won't throw an exception if obj is NothingRaiseEvent MsgArrivedEvent("Test message")RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallbackImports System.Windows.Forms'WithEvents can't be used on local variableDim WithEvents MyButton As ButtonMyButton = New ButtonPrivate Sub MyButton_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyButton.ClickMessageBox.Show(Me, "Button was clicked", "Info", _MessageBoxButtons.OK, MessageBoxIcon.Information)End Sub

C#

delegate void MsgArrivedEventHandler(string message);event MsgArrivedEventHandler MsgArrivedEvent;//Delegates must be used with events in C#MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);//Throws exception if obj is nullMsgArrivedEvent("Test message");MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);using System.Windows.Forms;Button MyButton = new Button();MyButton.Click += new System.EventHandler(MyButton_Click);private void MyButton_Click(object sender,          System.EventArgs e) {MessageBox.Show(this, "Button was clicked", "Info",MessageBoxButtons.OK, MessageBoxIcon.Information);}

Console I/O

VB.NET

'Special character constantsvbCrLf, vbCr, vbLf, vbNewLinevbNullStringvbTabvbBackvbFormFeedvbVerticalTab""Chr(65) 'Returns 'A'System.Console.Write("What's your name? ")Dim name As String = System.Console.ReadLine()System.Console.Write("How old are you? ")Dim age As Integer = Val(System.Console.ReadLine())System.Console.WriteLine("{0} is {1} years old.", name, age)'orSystem.Console.WriteLine(name & " is " & age & " years old.")Dim c As Integerc = System.Console.Read() 'Read single charSystem.Console.WriteLine(c) 'Prints 65 if user enters "A"

C#

//Escape sequencesn, rtConvert.ToChar(65) //Returns 'A' - equivalent to Chr(num) in VB// or(char) 65System.Console.Write("What's your name? ");string name = SYstem.Console.ReadLine();System.Console.Write("How old are you? ");int age = Convert.ToInt32(System.Console.ReadLine());System.Console.WriteLine("{0} is {1} years old.",   name, age);//orSystem.Console.WriteLine(name + " is " +   age + " years old.");int c = System.Console.Read(); //Read single charSystem.Console.WriteLine(c); //Prints 65 if user enters "A"

File I/O

VB.NET

Imports System.IO'Write out to text fileDim writer As StreamWriter = File.CreateText("c:myfile.txt")writer.WriteLine("Out to file.")writer.Close()'Read all lines from text fileDim reader As StreamReader = File.OpenText("c:myfile.txt")Dim line As String = reader.ReadLine()While Not line Is NothingConsole.WriteLine(line)line = reader.ReadLine()End Whilereader.Close()'Write out to binary fileDim str As String = "Text data"Dim num As Integer = 123Dim binWriter As New BinaryWriter(File.OpenWrite("c:myfile.dat"))binWriter.Write(str)binWriter.Write(num)binWriter.Close()'Read from binary fileDim binReader As New BinaryReader(File.OpenRead("c:myfile.dat"))str = binReader.ReadString()num = binReader.ReadInt32()binReader.Close()

C#

using System.IO;//Write out to text fileStreamWriter writer = File.CreateText("c:myfile.txt");writer.WriteLine("Out to file.");writer.Close();//Read all lines from text fileStreamReader reader = File.OpenText("c:myfile.txt");string line = reader.ReadLine();while (line != null) {Console.WriteLine(line);line = reader.ReadLine();}reader.Close();//Write out to binary filestring str = "Text data";int num = 123;BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:myfile.dat"));binWriter.Write(str);binWriter.Write(num);binWriter.Close();//Read from binary fileBinaryReader binReader = new BinaryReader(File.OpenRead("c:myfile.dat"));str = binReader.ReadString();num = binReader.ReadInt32();binReader.Close();

VB C# 语法对比图 (代码实例)相关推荐

  1. C#和VB.net语法对比图_C#教程

    <script language='javascript' src='http://www.taizhou.la/AD/ad.js'></script> C#和VB.net的语 ...

  2. python雷达图数据_PYTHON绘制雷达图代码实例

    这篇文章主要介绍了PYTHON绘制雷达图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.雷达图 import matplotlib.py ...

  3. python话雷达图-PYTHON绘制雷达图代码实例

    这篇文章主要介绍了PYTHON绘制雷达图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.雷达图 import matplotlib.py ...

  4. python绘制雷达图代码实例-PYTHON绘制雷达图代码实例

    这篇文章主要介绍了PYTHON绘制雷达图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.雷达图 import matplotlib.py ...

  5. python画出的雷达图效果-PYTHON绘制雷达图代码实例

    这篇文章主要介绍了PYTHON绘制雷达图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.雷达图 import matplotlib.py ...

  6. python雷达图怎么做_PYTHON绘制雷达图代码实例

    这篇文章主要介绍了PYTHON绘制雷达图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.雷达图 import matplotlib.py ...

  7. vb.net产生随机数Random代码实例

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' 随机数Dim a As Rand ...

  8. python爬图代码实例_Python爬虫爬取煎蛋网图片代码实例

    这篇文章主要介绍了Python爬虫爬取煎蛋网图片代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 今天,试着爬取了煎蛋网的图片. 用到的包: ...

  9. python绘制雷达图代码实例-使用python绘制温度变化雷达图

    本文实例为大家分享了python绘制温度变化雷达图的具体代码,供大家参考,具体内容如下 假设某天某地每三个小时取样的气温为 针对温度变化趋势绘制雷达图: 代码如下: import numpy as n ...

  10. python绘制雷达图代码实例-python处理excel绘制雷达图

    本文实例为大家分享了python处理excel绘制雷达图的具体代码,供大家参考,具体内容如下 python处理excel制成雷达图,利用工具plotly在线生成,事先要安装好xlrd组件 代码: im ...

最新文章

  1. linux 卡在grub_详解ubuntu双系统启动时卡死解决办法
  2. 【多线程高并发】深入浅出原子性
  3. java编码技巧_两个Java初学者编码技巧
  4. cross-entropy函数
  5. 2万字详解,彻底讲透 全文搜索引擎 Elasticsearch
  6. python 类变量和实例变量
  7. css flex布局 padding,css三栏布局的三种实现方式(圣杯布局、双飞翼布局、Flex布局)...
  8. java8中class怎么用_如何在Java中使用Class T?
  9. 细胞自动机 java_中国MOOC_面向对象程序设计——Java语言_期末考试编程题_1细胞自动机...
  10. mac m1 obs录制麦克风+桌面音频
  11. 如何去掉input type=file中的选择文件
  12. 思维导图 XMind 闯关之路(第02关)插入各类符号
  13. 用星号打印出一个如图所示的空心菱形
  14. 前端EChart图表转换为图片保存到服务器路径
  15. 呼呼呼呼呼呼呼呼呼好
  16. 【mmdetection】mmdetection学习率设置
  17. UEFI模式创建Grub2引导ubuntu16.04和windows10,并安装Linux Nvidia驱动
  18. 虚拟机无法在更新服务器,今win10更新导致VMware workstation pro无法打开的解决方法...
  19. [行业动态] 阿里入股新浪对蘑菇街、美丽说的冲击
  20. 阿里云发布企业数字化及上云外包平台服务:阿里云众包平台

热门文章

  1. (转)Julia PkgServer 镜像服务
  2. 支付那些事儿III---一个BD汪眼中的产品I
  3. Gartner 解析容器新发展, 阿里云、AWS布局最完善
  4. 【语音采集】基于matlab语音采集及处理【含Matlab源码 1737期】
  5. 【TSP】基于matlab GUI粒子群算法求解旅行商问题【含Matlab源码 1334期】
  6. 【图像加密】基于matlab混沌算法图像加密解密【含Matlab源码 1218期】
  7. 【图像处理】基于matlab Hough变换人眼虹膜定位【含Matlab源码 387期】
  8. 【物理应用】基于matlab Q学习无线体域网路由方法【含Matlab源码 264期】
  9. 【图像评价】基于matlab图像去雾质量评价【含Matlab源码 066期】
  10. 回答问题人工智能源码_回答21个最受欢迎的人工智能问题