开发者

Difference in creating an instance between VB.NET & C#

I am converting some code from VB.NET to C#. In VB.NET, I have this code:

Dim ind As Foo.Index
Dim ed As Foo.Edit
ind = New Foo.Index
ed = ind.InFunction()

That works. So in C# my code will look like this:

Foo.Index ind;
Foo.Edit ed;
ind = New Foo.Index();
ed = ind.InFunction();

But this doesn't work. I am sure that I did not forget to import namespaces. And now I've been wondering, is there any difference between 开发者_JAVA技巧those two?

EDIT: And I finally add

ed = New Foo.Edit();

into my C# code, but it also doesn't work. IMHO, I think there is a feature in VB.NET that allows auto initializing in variables (like the comment from Bex below suggests). Is it true?

FINAL: Seems I do need to show all the code. But I need to talk directly to you as well (or you just install the software of mine). It makes me really confused. Thank you all. Sorry for this kind of newbie question.


C-like languages (like C#) require you follow the pattern of [type] [variable name] at a minimum. C#, using the simplest form of initialization, requires you to use the new keyword.

A simple C# class definition:

class Foo
{
    public Foo()
    {
    }
}

Then, to initialize an instance:

Foo myFooIsStrong = new Foo();


//instantiation

IndexServer.ClientInfo ci = new  IndexServer.ClientInfo();

IndexServer.IXServicePortC konst = new IndexServer.IXServicePortC();

IndexServer.IndexServer ix = new IndexServer.IndexServer();

IndexServer.EditInfo ed = new IndexServer.EditInfo();


I don't quite understand what you are asking but this may help. VB auto initializes a lot of variables and c# doesn't. So in c# you should initialize your variables.


The problem is that vb.net let's you import namespace roots, while C# requires you to import the full namespace. Your VB code has a statement like this at the top:

Imports MyLibrary

This puts the MyLibrary namespace sort of "in scope", such that you can use the type MyLibrary.Foo.Index either through the full name or by simply saying Foo.Index. C# does not allow this. You must either also import MyLibrary.Foo or reference the entire name in your code.


C# is case sensitive. So the

ed = New Foo.Edit();

should be

ed = new Foo.Edit();


Here's an example

using IndexServer;

...

IndexServer ix = new IndexServer();
ClientInfo ci = new ClientInfo();
EditInfo ed = ix.checkoutSord(ci, Konstanta.EDIT_INFO.mbSord, Konstanta.LOCK.NO);

Without knowing what those classes look like, hard to tell you more. But instantiation is basically the same, just need to change some syntax for declaring variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜