Post (Tianji Forum): code skin replacement-C # and VB

Source: Internet
Author: User
Post (Tianji Forum): code skin replacement-C # and VB

Nowadays, the popular program "skin change" is to change the operation interface, and of course the program is still the original program. Code porting can also be called a "skin replacement". The content is not changed, but it becomes another language. This article describes how to port C # And VB.net, the hottest one today.

It is reasonable to say that there is no need to port these two languages, because the code they generate can be completely universal. However, if a project is basically written in VB but requires a few existing C # processes, using components is not a very efficient method. Even if you are studying C # Or VB, you can use existing code twice by porting them (for example, for fun donkey.net, only the vb version is available ).

Some people have compared these two languages and come to the conclusion that they are very similar. However, even so, beginners of VB see such as (button) sender ). TEXT = "start"; and Other syntaxes do not know how to port to VB, while C # beginners will also feel a headache for porting handles button1.click. Let's take a look at the most difficult part of their migration:

1. Option statement. The option Statement of VB can enable or disable the variable declaration check and type conversion check. In particular, after option strict is disabled, VB becomes a weak type language. Many types of conversions are automatic and porting to C # produces numerous errors. Therefore, if you want to port the vbprogram with the option strict off statement to C #, you 'd better enable option strict in VB first, and then change the places where all types of conversions are wrong to forced conversions, and then perform the transplantation.

2. type conversion. VB provides many types of Conversion Function operators, such as CINT (), csng (), and CSTR (). in C #, you only need to use (INT), (float ), (string. However, if it is not a standard type, the following C # statement:

(System. Button) sender). Text = "start ";

The function type operator ctype of VB is required. The correct method for porting the above Code is:

Ctype (sender, system. Button). Text = "start"

Do not use the method recommended by some people to disable option strict and then bind the method to call the sender object later. This does not meet the requirements that cannot be changed by program porting.

3. modifier and attribute label. The modifiers of VB and C # are completely equivalent, but the spelling is often different, which brings a lot of trouble to the porting, especially when the keywords representing the same meaning are completely different from the literal understanding. The keyword corresponding to VB and C # is given below:

VB
C #
VB
C #

Inherits
:
Implements
:

Mustinherit
Abstract
Notinheritable
Sealed

Overridable
Virtual
Notoverridable
Sealed

Mustoverride
Abstract
Overrides
Override

[Overloads]
None
Shadows
New

Shared
Static
Public
Public

Protected
Protected
Friend
Internal

Protected friend
Protected internal
Private
Private

Static
Implement with other methods
Byval
None

Byref
Ref
Optional
None

Paramarray
Params
Unable to implement
Unsafe

Unable to implement
Fixed


It can be seen that the keyword of VB is relatively long, and it is more rigorous than C. When porting data from C # to VB, pay attention to which VB has the keyword while C # does not, and the spelling in C # is the same, different keywords (such as mustoverride and mustinherit) are spelled in VB ). Some keywords, such as unsafe, cannot be transplanted to VB if C # uses them. Fortunately, these keywords are not frequently used in commercial applications.

Attribute tags are very similar in these two languages, so there should be no difficulty in Porting, as long as you know that the attribute tag is represented by square brackets [] in C, angle brackets are used in VB <>. In addition, if you want to use the name together to pass the parameter, C # directly uses the = sign, while VB uses the: = (colon and equal sign ).

4. Delegate type. The delegate type is a safe function pointer type. In C #, it is difficult to tell whether the function pointer is working or the function itself is working because their syntax is the same. When copying a variable of the delegate type, it is equivalent to a function, for example:

Public Delegate void functype (Object E)

...

Functype func;

Func = new functype (this. samplefunction1 );

// Call

Func (something );

// Point to another function

Func = This. samplefunction2

However, in VB, the delegate type is like a general object, and its method is obviously different from the function itself. You cannot assign the process name to a delegate type object directly, but you must use the addressof operator. The following example is the vb version of the C # program above. Note the implementation differences:

Public Delegate sub functype (byval e as object)

...

Dim func as functype

Func = new functype (addressof me. samplefunc1)

'Call

Func. Invoke (something)

'Point to another function.

Func = addressof me. samplefunction2

5. event handling. This is one of the biggest differences between the two languages. VB inherits the powerful event processing mechanism of previous versions, and many syntaxes are more flexible than C. Fortunately, in whatever circumstances, they can be transplanted to each other.

For event definition, both languages are a delegate type plus an event attribute, such:

[C #]

Public Delegate void myeventhandler (Object sender, eventargs E );

Public event myeventhandler myevent;

[Visual Basic]

Public Delegate sub myeventhandler (byval sender as object, byval e as eventargs)

Public event myevent as myeventhandler

VB also supports another more compact definition method with only one statement:

Public event myevent (byval sender as object, byval e as eventargs)

During migration, you must separate the parameters to form a delegate type, and then define the event according to the common method.

C #, like Delphi, is used to dynamically bind events. Its syntax is similar to the following:

Internal myclass myobj;

...

Myobj = new myclass ();

...

Myobj. myevent + = This. myobj_myevent;

...

Protected void myobj_myevent (Object sender, eventargs E)

{

// Statement

}

We can see that C # uses operators to connect the event process and event attributes. You can also use the-= Operator to unbind the event process from the event attribute. VB does not support Operator overloading, but it still supports this dynamic binding event process by using the addhandler and removehandler keywords. As shown in the above section, you can port it:

Addhandler myobj. myevent, addressof me. myobj_myevent

The unbinding syntax is similar to this, except that the keyword is removehandler. Do not forget that there is an addressof keyword before the process!

The dynamic binding event process is slow. VB supports a faster static binding event process. Once a static event process is set for the object, the binding cannot be unbound. This is generally the case. Syntax:

'Use the withevents keyword when defining variables.

Friend withevents myobj as myclass

'Directly write the event process. Pay attention to the handles Syntax:

Protected sub myobj_myevent (byval sender as object, byval e as eventargs )_

Handles myobj. myevent

'Statement

End sub

It indicates that the myobj_myevent process only responds to the myobj. myevent process. If a process responds to many events, column them behind handles and separate them with commas (,), such as handles event1, event2 ,...

In this case, we need to see all the objects and events behind handles and rewrite them one by one into dynamically bound statements:

Protected sub XXX (...) handles myobj1.myevent, myobj2.myevent

==>

Myobj1.myevent + = This. xxx;

Myobj2.myevent + = This. xxx;

...

Protected void XXX (...){}

When there are a large number of events, C # becomes much more troublesome. Fortunately, there are not many situations in which a process responds to a large number of events. (However, I wrote a process for 8 events, porting is troublesome !). In principle, porting a static event process to a dynamic event process does not fully comply with the porting rules, but I guess they do not have much difference in implementation principles, so don't worry.

6. Exception Handling. VB supports two types of exceptions:. NET Framework exceptions and VB's own error numbers. C # only supports the first type. Programs that use the wrong numbers of VB cannot be transplanted to C #, so try to use exceptions of the. NET Framework, as shown in the following VB statement:

Try

'Error code

Catch when err. Number = 52

'Code to solve the error

End try

This Code cannot be directly transplanted to C #. It can be smoothly transplanted only when the exception object is replaced by the ERR Object to obtain the exception information. In addition, the when Statement of VB gives the try statement a very flexible usage. It must be very skillful to implement it in C #. This requires a detailed analysis of the problem.

VB supports the exit try statement, which can jump directly from the try block or catch block to the Finally block. C # You can use the following tips if similar syntaxes are not provided:

[Visual Basic]

Try

'Some statements

Exit try

Finally

'Some statements

End try

[C #]

Try

{

// Some statements

Goto _ leave;

}

Finally

{

// Some statements

}

_ Leave: // do not forget to leave it here!

In short, the exit try statement is simulated with the GOTO statement by taking advantage of the features that cannot be skipped by finally blocks.

If the vbprogram uses the error handling implemented by the on error GOTO statement specific to VB, the problem will be troublesome. The Code may jump up or down during the process, and the statement execution method cannot be anticipated. This kind of code is a headache, not to mention porting. In general, all the statements are transferred to the try block, and then catch is used to handle errors one by one. When the resume statement is to be returned, you have to copy the code. It is not an easy task. Just change it slowly.

7. modules. VB support module, which is not supported by C. It does not matter, as long as a abstract class is created in C # And all members are shared, it is the same as the module. Of course, you cannot directly access the members in the module like VB. You need to use "class name. member name.

8. interfaces. C # It is not as powerful as VB in terms of interfaces (Why isn't such an important function even better ?), VB uses implements statements in combination with interface members and class implementation members, while C # uses names. Therefore, VB can modify the access level and name of the implementation member, while C # cannot change the name. When porting C # to VB, you 'd better use the VB.net editor to directly implement the interface, which is relatively simple. When we port VB to C #, we have to change all the changed names. In this case, we hate name conflicts. (at this time, I almost don't want to port it to C # any more ). Here is an example:

[Visual Basic]

Public class class1: Implements imyinterface

Public sub dosomething () implements imyinterface. Method1

End sub

End Class

[C #]

Public class class1: imyinterface

{

Public void Method1 ()

{

}

}

9. Operator overloading. This is a headache for VB. Since VB does not support Operator overloading, you must use subprograms and functions to simulate operators. For example, the plus and minus methods are used to simulate the + and-operations. Of course there are still many cases (for example, when the explicit it and implicit statements are met), there is really no way to do it, so we have to stop porting it. Operator Overloading is a very good function, which can make a lot of Operations simple, if VB supports it, it is really a perfect language.

Well, I think the most troublesome part has been done, and the rest is simple copy. Although I haven't made it clear in some places, I have basically clarified the differences between the two languages (I think there are quite a lot of differences), and there is no need to transplant large projects anyway, the main purpose of understanding this content is to take advantage of the existing code by double. I hope this article will be useful to you. Due to poor level, please correct me if you have any mistakes.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.