c#尝试从VB转换语句问题

时间:2011-09-06 22:10:02

标签: c# vb.net

我有这段代码在Web服务中调用一些函数。然而原版是用VB编写的,当我转换它时,它给我一个错误,我的c#说明'当前上下文中不存在名称信息'我检查了VB并且它在那里赢了!有什么想法吗?

代码

try {
        Atlas.ah21 oAh21 = new Atlas.ah21();
        oAh21.session_id = sessionID;
        oAh21.input = txtPostcode.Text;
        oAh21.data = "";
        Atlas.arrayOfAddress oAddresses = oAtlas.ah21(oAh21);

        int x = 0;
        int y = 0;
        string s = null;

    for (x = 0; x <= oAddresses.address.Length - 1; x++)
    {
        s = "";
        for (y = 0; y <= Information.UBound(oAddresses.address(x).LABEL.item); y++)
        {
            if (s.Length > 0)
            {
                s = s + ", ";
            }
            s = s + oAddresses.address(x).LABEL.item(y);
        }
        lstMatches.Items.Add(s);
    }

        txtStatus.Text = "Ready. ";

        if (oAddresses.address.Length > 1) {
            txtStatus.Text = txtStatus.Text + Convert.ToString(oAddresses.address.Length) + " matches found.";
        } else {
            txtStatus.Text = txtStatus.Text + Convert.ToString(oAddresses.address.Length) + " match found.";
        }
} catch {
    txtStatus.Text = "Error";
} finally {
        btnSearch.Enabled = true;
}

请原谅代码的数量,但我认为在这个问题的背景下是必要的。

5 个答案:

答案 0 :(得分:2)

Information类是为VB编写的特殊帮助程序模块,默认情况下在C#项目中不可用。但是,如果您引用Microsoft.VisualBasic程序集并在类中添加using Microsoft.VisualBasic;,则仍可以使用它。

如果将Microsoft.VisualBasic.dll程序集添加到项目中,将编译并运行以下简单的C#代码段:

using System;
using Microsoft.VisualBasic;

public class MyClass
{
    public static void Main()
    {
        Microsoft.VisualBasic.Information.IsDate("");
    }
}

如果您按照上述两个步骤操作,Information.UBound函数也会正常编译。

答案 1 :(得分:1)

我认为Information.UBound应该是静态调用。您是否通过文件顶部的Information语句包含了所需的命名空间(即包含using类型的命名空间)?例如:

namespace Whatever
{
    class Information { }
}

// in your file

using Whatever;  // now the Information class is visible in your file

答案 2 :(得分:1)

我真的不懂VB但是我认为UBound只是返回集合的长度所以你会这样做

for (y = 0; y <= oAddresses.address[x].LABEL.item.Length; y++)

除了你的评论,我已经意识到地址(x)应该是地址[x]。在c#中,你只使用()进行方法调用,索引器使用[]。在VB中,他们都使用()我认为。

答案 3 :(得分:0)

VB UBound相当于c#Array.GetUpperBound(...),请参阅http://msdn.microsoft.com/en-us/library/system.array.getupperbound.aspx。所以UBound的c#实现就是这样的:

public static int UBound(Array array, int dimension)
{
    if (Array == null)
    {
        throw new ArgumentNullException("array");
    }

    return array.GetUpperBound(dimension-1);
}

答案 4 :(得分:0)

对VB使用UBound但C#将其删除并在参数后添加长度。

<强> VB

For i = 0 To UBound(params)
   cmd.Parameters.Add(params(i))
Next (i)

<强> C#

for (i = 0; i <= @params.Length; i++)
  {
    cmd.Parameters.Add(@params[i]);
  }

谢谢, Fadão