[英]Difference in creating an instance between VB.NET & C#
我正在將一些代碼從VB.NET轉換為C#。 在VB.NET中,我有以下代碼:
Dim ind As Foo.Index
Dim ed As Foo.Edit
ind = New Foo.Index
ed = ind.InFunction()
這樣可行。 因此,在C#中,我的代碼將如下所示:
Foo.Index ind;
Foo.Edit ed;
ind = New Foo.Index();
ed = ind.InFunction();
但這是行不通的。 我確信我不會忘記導入名稱空間。 現在我一直在想,這兩者之間有什么區別嗎?
編輯:我終於添加
ed = New Foo.Edit();
到我的C#代碼中,但是它也不起作用。 恕我直言,我認為VB.NET中有一個功能可以自動初始化變量(如下面Bex的注釋所示)。 是真的嗎
最后:看來我確實需要顯示所有代碼。 但是我也需要直接與您交流(或者您只需安裝我的軟件)。 這讓我真的很困惑。 謝謝你們。 對不起,這種新手問題。
類似C的語言(如C#)要求您至少遵循[ 類型 ] [ 變量名 ]的模式。 C#使用最簡單的初始化形式,要求您使用new
關鍵字。
一個簡單的C#類定義:
class Foo
{
public Foo()
{
}
}
然后,初始化一個實例:
Foo myFooIsStrong = new Foo();
C#區分大小寫。 所以
ed = New Foo.Edit();
應該
ed = new Foo.Edit();
//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();
我不太了解您的要求,但這可能會有所幫助。 VB自動初始化很多變量,而c#不會。 因此,在C#中,您應該初始化變量。
問題是vb.net讓我們導入名稱空間根,而C#要求您導入完整名稱空間。 您的VB代碼頂部具有以下語句:
Imports MyLibrary
這使MyLibrary命名空間處於“范圍內”,這樣您就可以通過全名或簡單地說Foo.Index
來使用類型MyLibrary.Foo.Index
。 C#不允許這樣做。 您還必須導入MyLibrary.Foo
或在代碼中引用全名。
這是一個例子
using IndexServer;
...
IndexServer ix = new IndexServer();
ClientInfo ci = new ClientInfo();
EditInfo ed = ix.checkoutSord(ci, Konstanta.EDIT_INFO.mbSord, Konstanta.LOCK.NO);
在不知道這些類是什么樣的情況下,很難告訴您更多信息。 但是實例化基本上是相同的,只需要更改一些聲明變量的語法即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.