C#和VB.net语法对比

18 篇文章 1 订阅

C#和VB.net的语法相差还是比较大的. 可能你会C#,可能你会VB.

将它们俩放在一起对比一下你就会很快读懂,并掌握另一门语言.

相信下面这张图会对你帮助很大.

Comments

VB.NET

 

‘Single line only

            Rem Single line only

 

C#

// Single line

            /* Multiple

            line */

            /// XML comments on single line

            /** XML comments on multiple lines */

Data Types

VB.NET

 

‘Value Types

            Boolean

            Byte

            Char (example: "A")

            Short, Integer, Long

            Single, Double

            Decimal

            Date

            ‘Reference Types

            Object

            String

            Dim x As Integer

            System.Console.WriteLine(x.GetType())

            System.Console.WriteLine(TypeName(x))

            ‘Type conversion

            Dim d As Single = 3.5

            Dim i As Integer = CType (d, Integer)

            i = CInt (d)

            i = Int(d)

 

C#

 

//Value Types

            bool

            byte, sbyte

            char (example: ‘A‘)

            short, ushort, int, uint, long, ulong

            float, double

            decimal

            DateTime

            //Reference Types

            object

            string

            int x;

            Console.WriteLine(x.GetType())

            Console.WriteLine(typeof(int))

            //Type conversion

            float d = 3.5;

            int i = (int) d

 

Constants

VB.NET

Const MAX_AUTHORS As Integer = 25

            ReadOnly MIN_RANK As Single = 5.00

C#

const int MAX_AUTHORS = 25;

            readonly float MIN_RANKING = 5.00;

Enumerations

VB.NET

Enum Action

              Start

              ‘Stop is a reserved word

            [Stop]

              Rewind

              Forward

            End Enum

            Enum Status

               Flunk = 50

               Pass = 70

               Excel = 90

            End Enum

            Dim a As Action = Action.Stop

            If a <> Action.Start Then _

            ‘Prints "Stop is 1"

               System.Console.WriteLine(a.ToString & " is " & a)

            ‘Prints 70

            System.Console.WriteLine(Status.Pass)

            ‘Prints Pass

            System.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 70

            System.Console.WriteLine((int) Status.Pass);

            // Prints Pass

            System.Console.WriteLine(Status.Pass);

Operators

VB.NET

 

‘Comparison

            =  <  >  <=  >=  <>

            ‘Arithmetic

            +  -  *  /

            Mod

              (integer division)

            ^  (raise to a power)

            ‘Assignment

            =  +=  -=  *=  /=  =  ^=  <<=  >>=  &=

            ‘Bitwise

            And  AndAlso  Or  OrElse  Not  <<  >>

            ‘Logical

            And  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 line

            If x <> 100 And y < 5 Then x *= 5 : y *= 2  

            ‘Preferred

            If x <> 100 And y < 5 Then

              x *= 5

              y *= 2

            End If

            ‘or to break up any long single command use _

            If henYouHaveAReally < longLine And _

            itNeedsToBeBrokenInto2   > Lines  Then _

              UseTheUnderscore(charToBreakItUp)

            If x > 5 Then

              x *= y

            ElseIf x = 5 Then

              x += y

            ElseIf x < 10 Then

              x -= y

            Else

              x /= y

            End If

            ‘Must be a primitive data type

            Select Case color   

              Case "black", "red"

                r += 1

              Case "blue"

                b += 1

              Case "green"

                g += 1

              Case Else

                other += 1

            End 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;

            else

              x /= y;

            //Must be integer or string

            switch (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 < 10

              c += 1

            End While Do Until c = 10

              c += 1

            Loop

            ‘Post-test Loop:

            Do While c < 10

              c += 1

            Loop

            For c = 2 To 10 Step 2

              System.Console.WriteLine(c)

            Next

            ‘Array or collection looping

            Dim names As String() = {"Steven", "SuOk", "Sarah"}

            For Each s As String In names

              System.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:

            do

              i++;

            while (i < 10);

            // Array or collection looping

            string[] 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 - 1

              Console.WriteLine(nums(i))

            Next

            ‘4 is the index of the last element, so it holds 5 elements

            Dim names(4) As String

            names(0) = "Steven"

            ‘Throws System.IndexOutOfRangeException

            names(5) = "Sarah"

            ‘Resize the array, keeping the existing

            ‘values (Preserve is optional)

            ReDim Preserve names(6)

            Dim twoD(rows-1, cols-1) As Single

            twoD(2, 0) = 4.5

            Dim 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 array

            string[] names = new string[5];

            names[0] = "Steven";

            // Throws System.IndexOutOfRangeException

            names[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 += 1

              y += 1

              z = 5

            End Sub

            ‘c set to zero by default

            Dim a = 1, b = 1, c As Integer

            TestFunc(a, b, c)

            System.Console.WriteLine("{0} {1} {2}", a, b, c) ‘1 2 5

            ‘Accept variable number of arguments

            Function Sum(ByVal ParamArray nums As Integer()) As Integer

              Sum = 0

              For Each i As Integer In nums

                Sum += i

              Next

            End 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 value

            Sub SayHello(ByVal name As String,

            Optional ByVal prefix As String = "")

              System.Console.WriteLine("Greetings, " & prefix

            & " " & name)

            End Sub

            SayHello("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 initializing

            TestFunc(a, ref b, out c);

            System.Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5

            // Accept variable number of arguments

            int 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 handling

            On Error GoTo MyErrorHandler

            ...

            MyErrorHandler: System.Console.WriteLine(Err.Description)

            Dim ex As New Exception("Something has really gone wrong.")

            Throw ex

            Try

              y = 0

              x = 10 / y

            Catch ex As Exception When y = 0 ‘Argument and When is optional

              System.Console.WriteLine(ex.Message)

            Finally

              DoSomething()

            End Try

 

C#





Exception up = new Exception("Something is really wrong.");

            throw up; // ha ha

            try{

              y = 0;

              x = 10 / y;

            }

            catch (Exception ex) { //Argument is optional, no "When" keyword

              Console.WriteLine(ex.Message);

            }

            finally{

              // Do something

            }

 

Namespaces

VB.NET

 

Namespace ASPAlliance.DotNet.Community

              ...

            End Namespace

            ‘or

            Namespace ASPAlliance

              Namespace DotNet

                Namespace Community

                  ...

                End Namespace

              End Namespace

            End Namespace

            Imports ASPAlliance.DotNet.Community

 

C#

 

namespace ASPAlliance.DotNet.Community {

              ...

            }

            // or

            namespace ASPAlliance {

              namespace DotNet {

                namespace Community {

                  ...

                }

              }

            }

            using ASPAlliance.DotNet.Community;

 

Classes / Interfaces

VB.NET

 

‘Accessibility keywords

            Public

            Private

            Friend

            Protected

            Protected Friend

            Shared

            ‘Inheritance

            Class Articles

              Inherits Authors

              ...

            End Class

            ‘Interface definition

            Interface IArticle 

              ...

            End Interface

            ‘Extending an interface

            Interface IArticle

              Inherits IAuthor

              ...

            End Interface

            ‘Interface implementation</span>

            Class PublicationDate

              Implements</strong> IArticle, IRating

               ...

            End Class

 

C#

 

//Accessibility keywords

            public

            private

            internal

            protected

            protected internal

            static

            //Inheritance

            class Articles: Authors {

              ...

            }

            //Interface definition

            interface IArticle {

              ...

            }

            //Extending an interface

            interface IArticle: IAuthor {

              ...

            }

            //Interface implementation

            class PublicationDate: IArticle, IRating {

               ...

            }

 

Constructors / Destructors

VB.NET

Class TopAuthor

              Private _topAuthor As Integer

              Public Sub New()

                _topAuthor = 0

              End Sub

              Public Sub New(ByVal topAuthor As Integer)

                Me._topAuthor = topAuthor

              End Sub

              Protected Overrides Sub Finalize()

               ‘Desctructor code to free unmanaged resources

                MyBase.Finalize()

              End Sub

            End 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 TopAuthor

            With author

              .Name = "Steven"

              .AuthorRanking = 3

            End With

            author.Rank("Scott")

            author.Demote() ‘Calling Shared method

            ‘or

            TopAuthor.Rank()

            Dim author2 As TopAuthor = author ‘Both refer to same object

            author2.Name = "Joe"

            System.Console.WriteLine(author2.Name) ‘Prints Joe

            author = Nothing ‘Free the object

            If author Is Nothing Then _

              author = New TopAuthor

            Dim obj As Object = New TopAuthor

            If TypeOf obj Is TopAuthor Then _

              System.Console.WriteLine("Is a TopAuthor object.")

 

C#

 

TopAuthor author = new TopAuthor();

            //No "With" construct

            author.Name = "Steven";

            author.AuthorRanking = 3;

            author.Rank("Scott");

            TopAuthor.Demote() //Calling static method

            TopAuthor author2 = author //Both refer to same object

            author2.Name = "Joe";

            System.Console.WriteLine(author2.Name) //Prints Joe

            author = null //Free the object

            if (author == null)

              author = new TopAuthor();

            Object obj = new TopAuthor(); 

            if (obj is TopAuthor)

              SystConsole.WriteLine("Is a TopAuthor object.");

 

Structs

VB.NET

 

Structure AuthorRecord

              Public name As String

              Public rank As Single

              Public Sub New(ByVal name As String, ByVal rank As Single)

                Me.name = name

                Me.rank = rank

              End Sub

            End Structure

            Dim author As AuthorRecord = New AuthorRecord("Steven", 8.8)

            Dim author2 As AuthorRecord = author

            author2.name = "Scott"

            System.Console.WriteLine(author.name) ‘Prints Steven

            System.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 = author

            author.name = "Scott";

            SystemConsole.WriteLine(author.name); //Prints Steven

            System.Console.WriteLine(author2.name); //Prints Scott

 

Properties

VB.NET

 

Private _size As Integer

            Public Property Size() As Integer

              Get

                Return _size

              End Get

              Set (ByVal Value As Integer)

                If Value < 0 Then

                  _size = 0

                Else

                  _size = Value

                End If

              End Set

            End Property

            foo.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 message

            As String)

            Event MsgArrivedEvent As MsgArrivedEventHandler

            ‘or to define an event which declares a

            ‘delegate implicitly

            Event MsgArrivedEvent(ByVal message As String)

            AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback

            ‘Won‘t throw an exception if obj is Nothing

            RaiseEvent MsgArrivedEvent("Test message")

            RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback

            Imports System.Windows.Forms

            ‘WithEvents can‘t be used on local variable

            Dim WithEvents MyButton As Button

            MyButton = New Button

            Private Sub MyButton_Click(ByVal sender As System.Object, _

              ByVal e As System.EventArgs) Handles MyButton.Click

              MessageBox.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 null

            MsgArrivedEvent("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 constants

            vbCrLf, vbCr, vbLf, vbNewLine

            vbNullString

            vbTab

            vbBack

            vbFormFeed

            vbVerticalTab

            ""

            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)

            ‘or

            System.Console.WriteLine(name & " is " & age & " years old.")

            Dim c As Integer

            c = System.Console.Read() ‘Read single char

            System.Console.WriteLine(c) ‘Prints 65 if user enters "A"

 

C#

 

//Escape sequences

            n, r

            t

            Convert.ToChar(65) 
//Returns ‘A‘ - equivalent to Chr(num) in VB

            // or

            (char) 65

            System.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);

            //or

            System.Console.WriteLine(name + " is " + 
 age + " years old.");

            int c = System.Console.Read(); //Read single char

            System.Console.WriteLine(c); 
//Prints 65 if user enters "A"

 

File I/O

VB.NET

 

Imports System.IO

            ‘Write out to text file

            Dim writer As StreamWriter = File.CreateText

              ("c:myfile.txt")

            writer.WriteLine("Out to file.")

            writer.Close()

            ‘Read all lines from text file

            Dim reader As StreamReader = File.OpenText

              ("c:myfile.txt")

            Dim line As String = reader.ReadLine()

            While Not line Is Nothing

              Console.WriteLine(line)

              line = reader.ReadLine()

            End While

            reader.Close()

            ‘Write out to binary file

            Dim str As String = "Text data"

            Dim num As Integer = 123

            Dim binWriter As New BinaryWriter(File.OpenWrite

              ("c:myfile.dat"))

            binWriter.Write(str)

            binWriter.Write(num)

            binWriter.Close()

            ‘Read from binary file

            Dim 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 file

            StreamWriter writer = File.CreateText

              ("c:myfile.txt");

            writer.WriteLine("Out to file.");

            writer.Close();

            //Read all lines from text file

            StreamReader 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 file

            string 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 file

            BinaryReader binReader = new BinaryReader(File.OpenRead

              ("c:myfile.dat"));

            str = binReader.ReadString();

            num = binReader.ReadInt32();

            binReader.Close();

 



◎代码编定实现Interface时
 
C#中使用 :Interface,然后按shift+alt+F10回车,呵呵,全部接口需实现的方法属性全部自动生成。当然这个是2005才有的。2003不知有没有,反正我是没有找着。况且2005也算是普遍了。
VB中使用 Implements,光标定位至相应的Interface的上面,直接回车,呵呵,比C#还少一步就自动生成接口需要实现的方法及属性了。

◎关键字对应关系: 
 

C#

VB.NET

using

Imports

this

Me

void

Sub

base

MyBase

abstract

MustInherit

sealed

NotOverridable

virtual

MustOverride

switch

Select

internal

Friend

static  

Shared  

<T>

(Of T)

◎文档注释

都是基于XML语法,可以描述代码中每一个类型和每一个成员的信息,我们知道书写XML文档注释最大的好处就是可以获得智能感知的支持,并结合特定的xlts生成漂亮的帮助文档,C#中连续输入///即会自动生成相对应的符合xml的注释出来。这点VB好像不成,VB中连续输和''',然后要手工写出符出xml格式的注释出来,一旦开始就不能断开,也不能掺杂其他代码元素,直到所有的XML标记被关闭。<summary>是VB推荐使用的标记,是该描述元素的摘要。 除了<summary>,常用的标记有<remark>,表示说明;<param>表示参数信息;< exception>表示异常,此外还有<include>和<permission>等等。当然也不一定非要使用这些推荐的标记的,但是这些标记使用时可以自动完成,而且能被IDE所利用,所以C#就可以在///之后自动生成。关于这一点。本人比较钟意C#多点。

◎My命名空间

"My"是一个极为出色的设计,是一个工程相关的命名空间,其中的内容是由IDE帮助组织的。这个可能是VB优于C#一个地方吧,至少到目前为此我所知道的,C#是没有这个命名空间。当然C#中的Properties是可以实现VB中的My.Resources和My.Settings,至于My.User、My.Forms和My.WebServices就真的没有了,要实现他们的功能,需要完全手工编码。 
My命名空间在当前版本中主要包含六个主要部分,分别是:My.Application、My.Computer、My.Resources、My.User、My.Forms和My.Webservices。直接输入My关键字就可找到他们,也可以导入My命名空间,其语法是: Imports 项目名称.My 

由于这是一项对于我来说是一项新的功能,查阅相关资料得到: 
My.Application是与当前运行的应用程序有关的对象,许多功能和Application对象是一样的,但是My.Application不仅仅能用于Windows Form的应用程序,许多功能在控制台应用程序照样能够使用。列表说明如下:

My. Application成员

功能描述

ApplicationContext

应用程序的上下文,包括主线程和主窗体的信息

AssemblyInfo

程序集信息,包括版本、版权、标题、产品名称和可执行名称等

ChangeCurrentCulture

改变应用程序当前文化设置,如货币和时间的格式

ChangeCurrentUICulture

改变应用程序当前的用户界面文化设置,如显示语言和用词

CommandLineArgs

一个只读集合,返回当前应用程序的命令行参数。这些参数已经分隔开,无须像原来那样手工分隔Command函数的值了

CurrentCulture

返回当前的文化设置

CurrentDirectory

返回应用程序使用的当前目录

CurrentUICulture

返回当前的用户界面文化设置

Deployment

返回按照ClickOnce方法部署的应用程序的Deployment对象

DoEvents

执行储存在Windows消息队列中的所有Windows消息

Exit

退出应用程序

GetEnvironmentVariable

通过环境变量的名字获取环境变量的值

IsNetworkDeployed

返回一个值,指示当前应用程序是否采用了网络部署方式

Log

一个记录应用程序事件日志和异常的日志工具

MainForm

当前应用程序的主窗体

OpenForms

当前应用程序中所有已经打开窗体的集合,与VB6的Forms集合功能相同

Run

启动Visual Basic的启动/关闭应用程序模式

SplashScreen

返回当前应用程序作为Splash Screen的窗口

My.Computer封装了大量访问系统和硬件信息的功能,操作起来比直接使用.NET Framework或Windows API都方便得多。包括很多对象,利用这些对象,以前要写N多代码的东东,现在可能一两行代码即可搞定。

My.Computer中的对象

功能描述

示例代码

My.Computer.Audio

提供了播放音频的功能,它既可以从wav等文件播放,也可以从音频数据流来播放,就是说你可以用它轻松播放储存在资源文件中或者数据库中的音频。播放时还可以指定后台播放或等待结束等多种设置。结合My.Resources来使用,更显得方便无穷。


My.Computer.Audio.Play("c:\ding.wav", AudioPlayMode.BackgroundLoop)

My.Computer.Clipboard

提供了以强类型方式读写剪贴板的功能,比Windows.Forms里面的剪贴板更加好用。使用Clipboard对象可以直接从剪贴板读写音频、图像、 文本甚至我的电脑中的文件拖放信息。此外,由VB6升级的项目现在将直接使用My.Computer.Clipboard对象升级以前的 Clipboard对象,这将解决VB.NET不能升级原先剪贴板功能的缺陷。


My.Computer.Clipboard.SetText(TextBox1.Text)

My.Computer.Clock

获取时间的工具,它可以直接获取当地时间、中时区的时间和从当时子时开始的毫秒计数。

My.Computer.FileSystem

充分改善文件操作的复杂程度。FileSystem对象提供了易于理解的操作方式。FileSystem对象中复制文件的方法不但只需要指定目标路径,还 可以帮助你建立目标目录中不存在的级别。它还特别提供了CopyDirectory的功能,可以复制整个目录!这正是目前.NET Framework缺乏的功能。同时FileSystem还能提供搜索上级目、子目录或根目录的功能,非常体贴。

 


My.Computer.FileSystem.DeleteFile("c:\mybigfile.big", TrueTrue

 


s = My.Computer.FileSystem.ReadAllText("c:\a.txt")


当然通过System.IO.FileSystem类也可以完成FileSystem对象的大多数功能,这种方式就类似于C#或者说更适合于C#了。

My.Computer.Info

获得本机物理内存或虚拟内存的总数,剩余量、操作系统名称、当前用户名、本机安装的文化设置等等,都可以轻松使用Info对象,它让你对应用程序所在的系统了如指掌。

My.Computer.Keyboard

和My.Computer.Mouse

快速获得用户键盘的信息,如大写锁定、数字键盘锁定等是否打开,以及鼠标有几个按键,是否配备滚轮等。如果你希望你的应用程序能够做到最体贴用户,那这些信息是少不了了


Dim f As Boolean = My.Computer.Mouse.ButtonsSwapped
My.Computer.Name'不用多说,这就是本机操作系统安装时输入的名称



My.Computer.Network

最常用的网络任务,只需要一行代码,就可以Ping一个地址,或者检测网络是否接通。

 


If My.Computer.Network.IsAvailable Then
    My.Computer.Network.DownloadFile("http://abc.com/x.zip", _
        "C:\download")
End If

 

My.Computer.Port

提供了用一行代码打开本机串口的功能,还能立刻绑定一个事件监视串口的变化。现在串口编程出奇的简单,再也不需要MSComm控件了。

My.Computer.Printers

能够遍历本机所安装的所有打印机,还能找出默认的打印机。通过向默认打印机画图一样的操作,就能开始打印了。这样的操作会让你想起VB6时代便利而简洁的 打印操作。下面的例子将在默认打印机上打印一个椭圆。从VB6升级项目时,原来的Printer对象将自动升级为 My.Computer.Printers中的相关操作,升级的用户可以更加放心了。

 


My.Computer.Printers.DefaultPrinter.DrawEllipse( _
    New RectangleF(2, 2, 50, 150), 1)
My.Computer.Printers.DefaultPrinter.Print()

 

My.Computer.Registry

比Microsoft.Win32空间中的那个版本简单多了,他提供强类型的路径支持,还能非常方便地读写注册表。


Dim exists As Boolean = True
Dim path As String = "Software\Microsoft\TestApp\1.0"
If My.Computer.Registry.CurrentUser.OpenSubKey(path) Is Nothing Then
    exists = False
End If

My.Computer.Screen

获取屏幕的可视范围,像素的位数等。比VB6的Screen对象更强的是,它现在支持两个显示器。

My.Resources不是一个类库,而是My命名空间中唯一一个子命名空间。是对项目资源的强类型封装,从而使的资源的使用变得非常简单。

My.User是My命名空间中最小的成员,和Thread.CurrentPrincipal属性有关。简单地将用户名和角色信息提供,如果要获得当前登录的用户名,只需要输入My.User.Identity就行了。

My.Forms感觉就是给VB6.0的用户找回一个以前的窗体编程模式, 因为My.Forms虽然在My命名空间中,但是使用它并不需要输入My.Forms。而且My.Forms为项目中每一个窗体维护了一个默认实例,其实现方法很像Singleton模式——每个窗体都有一个默认实例,而且有一个全局访问点,就通过窗体的类名即可访问到。假设有两个窗体——Form1和Form2,Form1是启动窗体,现在你要用代码显示Form2,只需Form2.Show即可。要在Form2中修改Form1中一个TextBox的文字,只需要这样:Form1.textBox1.Text = "Hello"即可。My.Forms的功能是解决窗体互访的最佳模式,同时也不会浪费内存,因为它只有在第一次访问所需窗体的时候才建立它。

My.WebServices原理同My.Forms一样。WebService对于项目全局应该有一个一致的访问点,所以VB2005将代替你创建代理类的实例,并维护于My.WebServices中,你可以随时访问他。

扩展My命名空间的功能

直接把类或模块放入My命名空间是个方便的方法,做法非常简单,只要将类或模块定义在My命名空间中即可,例如:

最简单的方法

然后就可以直接用My.Tools来访问自定义的模块,这种是将函数做成静态的,但所有的方法都做成静态毕竟不是最佳方法,所以资料推荐的做法是:首先我们要定义自定义类,可以放在任何地方,而不必放到My命名空间中,这样就可以避免类名直接显示在My关键字后。然后,在My命名空间下,定义一个带有HideModuleNameAttribute的模块,名称可以随便起;最后在模块中设定访问自定义类实例的属性。

利用Partial关键字可以扩展My.Application或My.Computer的功能。其对应的Class分别为MyApplication和MyComputer。

在C#中使用My.Application要使用My.Application,必须要继承System.Windows.Forms.WindowsFormsApplicationBase (该类位于Microsoft.VisualBasic.dll中)。继承之后我们要做几件事情,首先书写构造函数初始化MyApplication类, 在Visual Basic中这些设置均为IDE生成,而C#则需要手工书写。然后重写OnCreateMainForm方法,这个方法设定了当前应用程序的主窗体。接下 来书写My类,让他提供对MyApplication类的全局访问点。最后改写Main,在其中执行My.Application.Run()代替原来的 Application.Run(),具体做法如下。

 


namespace WindowsApplication2.Properties
{
    
public class MyApplication : WindowsFormsApplicationBase
    
{
        
public MyApplication() : base(AuthenticationMode.Windows)
        
{
            IsSingleInstance 
= false;
            EnableVisualStyles 
= true;
            ShutdownStyle 
= ShutdownMode.AfterMainFormCloses;
        }



        
protected override void OnCreateMainForm()
        
{
            
//Sepecify the main form of your project
            MainForm = new WindowsApplication2.Form1();
        }


    }


    
public static class My
    
{
        
private static MyApplication _Application;
        
private static object syncRoot = new object();

        
public static MyApplication Application
        
{
            
get {
                
if (_Application == null)
                
{
                    
lock (syncRoot)
                    
{
                        
if (_Application == null)
                        
{
                            _Application 
= new MyApplication();
                        }

                    }
 // end lock
                }
 // end if
                return _Application; 
            }
 // end get
        }


    }

}
 

修改Main函数

 

[STAThread]
static   void  Main()
{
    
// Application.EnableVisualStyles();
    
// Application.EnableRTLMirroring();
    
// Application.Run(new Form1());
    Properties.My.Application.Run();
}
 

 


最后,再將自己對於事件機制的一小段代碼貼在這里,算是自己的筆記吧,另開一個隨筆又有閑太過於勉強,看這篇反正是講VB VS C#的,想放在這里也未嘗不可:

 


''' <summary>
'
'' 申明代理
'
'' </summary>
'
'' <param name="sender"></param>
'
'' <param name="e"></param>
'
'' <remarks></remarks>
Delegate Sub myEvnetHandler(ByVal sender As ObjectByVal e As EventArgs)

''' <summary>
'
'' 創建事件發布者類,所需做的事情有:
'
'' 1、申明事件
'
'' 2、檢測事件是事存在的方法(可有可無)
'
'' 3、事件調用
'
'' </summary>
'
'' <remarks></remarks>
Class Release
    
Public Event myEvent As myEvnetHandler
    
Public Sub DomyEvent()
        
RaiseEvent myEvent(NothingNothing)
    
End Sub

End Class


''' <summary>
'
'' 創建事件接收者類,所需做的事情:
'
'' 利用代理將對象及其方法注冊進事件
'
'' </summary>
'
'' <remarks></remarks>
Class Receive
    
Public Sub New(ByVal rl As Release)
        
AddHandler rl.myEvent, AddressOf OnmyEvent
    
End Sub

    
Sub OnmyEvent(ByVal sender As ObjectByVal e As EventArgs)
        Console.WriteLine(
"VB Event Raise")
        Console.ReadLine()
    
End Sub

End Class


''' <summary>
'
'' 實例化發布者、訂閱者類,並引發事件
'
'' 事件只能還發布者調用,接收者注冊
'
'' </summary>
'
'' <remarks></remarks>
Module Module1
    
Sub Main()
        
Dim R As Release = New Release()
        
Dim C As Receive = New Receive(R)
        R.DomyEvent()
    
End Sub

End Module

 


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    
/// <summary>
    
/// 申明代理
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>

    delegate void myEventHandler(object sender,EventArgs e);

    
/// <summary>
    
/// 創建事件發布者類,所需做的事情有:
    
/// 1、申明事件
    
/// 2、檢測事件是事存在的方法(可有可無)
    
/// 3、事件調用
    
/// </summary>

    class Release
    
{
        
public event myEventHandler myEvent;
        
public void DomyEvent()
        
{
            
if (myEvent != null)
            
{
                myEvent(
nullnull);
            }

        }

    }


    
/// <summary>
    
/// 創建事件接收者類,所需做的事情:
    
/// 利用代理將對象及其方法注冊進事件
    
/// </summary>

    class Receive
    
{
        
public Receive(Release rl)
        
{
            rl.myEvent 
+= new myEventHandler(rl_myEvent);
        }


        
void rl_myEvent(object sender, EventArgs e)
        
{
            Console.WriteLine(
"C# Event Raised");
            Console.ReadLine();
        }

    }


    
/// <summary>
    
/// 實例化發布者、訂閱者類,並引發事件
    
/// 事件只能還發布者調用,接收者注冊
    
/// </summary>

    class Program
    
{
        
static void Main(string[] args)
        
{
            Release R  
= new Release();
            Receive C 
= new Receive(R);
            R.DomyEvent();
        }

    }

}

 

分类:  ASP.NET

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET 4 是微软推出的一种用于构建动态网站和 Web 应用程序的开发框架。它是ASP.NET技术的升级版本,提供了更多的高级编程功能。在ASP.NET 4高级编程中,开发人员可以利用新特性和功能来更好地完成项目,并优化性能。 首先,在ASP.NET 4中,引入了一些新的控件,如GridView、Repeater等,这些控件使开发人员能够更加方便地处理数据绑定和呈现,减少了编写重复代码的工作。另外,还可以自定义控件,并使用控件模板来定制页面外观。 其次,ASP.NET 4还引入了一些新的特性,如扩展语法,可以使用C#VB.NET编写更简洁的代码。还可以使用动态数据进行数据访问,简化了数据库操作。同时,还提供了新的验证控件和模型绑定,使数据验证和处理更加方便。 此外,ASP.NET 4还提供了一些性能优化功能。例如,输出缓存可以缓存页面输出,减少重复计算,提高页面加载速度。还可以使用新的ViewState模式来减少页面传输的数据量,提高页面的响应速度。 在安全方面,ASP.NET 4引入了更强大的安全功能。例如,可以使用表单验证和角色管理来实现用户认证和授权。还可以使用ASP.NET的内置防止跨站点脚本攻击功能,保护网站免受恶意脚本的攻击。 总之,ASP.NET 4高级编程为开发人员提供了更多的工具和功能来简化开发工作,并提高了网站和Web应用程序的性能和安全性。开发人员可以根据项目的需求和业务逻辑,灵活应用这些功能,打造出高质量的Web应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值