如何将数组作为ref参数传递

时间:2016-02-26 19:57:12

标签: c# vb.net

我感谢一些帮助将下面的VB代码翻译成C#。 我被困在obSMS.GetEstado(vMessages)。我正在调用一个应该重新调用vMessages的外部服务, 一个类似于底部描述的数组。该数组的每一行都有4个元素(0,1,2 3)。 请问如何将obSMS.GetEstado(vMessages)转换为C#。

非常感谢

Dim obSMS As SMSEmpresarial.clsSMS
Dim vMessages As Object
Dim i As Integer

obSMS = New SMSEmpresarial.clsSMS
obSMS.GetEstado(vMessages)
For i = 0 To UBound(vMessages, 1) - 1
   Me.ListBox1.Items.Add("Cod:" & CStr(vMessages(i, 0)) &
   ":Tel:" & CStr(vMessages(i, 1)) & ":Est:" & CStr(vMessages(i, 2)) &
   ":Obs:" & CStr(vMessages(i, 3)))
Next
obSMS = Nothing
Exit Sub

vMessages数组的外观如下:

|row 0    |AAAAA   |BBBBB    |CCCCC   |DDDD
|row 1    |KKKKK   |PPPPP    |GGGGG   |HHHH
|row 2    |MMMMM   |FFFFF    |XXXXX   |ZZZZ

2 个答案:

答案 0 :(得分:1)

这应该是您的代码的直接翻译。为了使这不仅仅是“给我答案”,我将继续解释翻译中发生的事情。首先是代码:

//Declaring and initializing obSMS. var keyword uses implicit typing.
var obSMS = new SMSEmpresarial.clsSMS();

//Declaring this as dynamic, because I have no clue what the eventual type will be.
dynamic vMessages = new object();
obSMS.GetEstado(ref vMessages);

foreach(var message in vMessages)
{
    //this replaces Me
    //+ is used to concatenate instead of &
    //[] is the index accessor in C#
    //ToString() is called instead of CStr()
    this.ListBox1.Items.Add("Cod:" + vMessages[0].ToString() + ":Tel:" + vMessages[1].ToString() + ":Est:" + vMessages[2].ToString() + ":Obs:" + vMessages[3].ToString());
}

最大的问题是我们不知道vMessages被更改为什么,所以我通过dynamic关键字使用后期绑定。当你没有与Com接口或动态的东西时.net中的后期绑定通常被认为是不好的做法...

答案 1 :(得分:0)

我希望,这将回答你问题的第一部分和最后一部分“我感谢一些帮助将下面的VB代码翻译成C#......” ... “我需要如何将obSMS.GetEstado(vMessages)转换为C#的int。“ http://converter.telerik.com/

SMSEmpresarial.clsSMS obSMS = default(SMSEmpresarial.clsSMS);
object vMessages = null;
int i = 0;

obSMS = new SMSEmpresarial.clsSMS();
obSMS.GetEstado(vMessages);
for (i = 0; i <= Information.UBound(vMessages, 1) - 1; i++) 
{
    this.ListBox1.Items.Add("Cod:" + Convert.ToString(vMessages(i, 0)) + ":Tel:" + Convert.ToString(vMessages(i, 1)) + ":Est:" + Convert.ToString(vMessages(i, 2)) + ":Obs:" + Convert.ToString(vMessages(i, 3)));
}
obSMS = null;
return;

//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================

第二部分,

obSMS.GetEstado(vMessages);

由于vMessages是对象,因此您需要在obSMS.GetEstado(ref p)初始化它。如果obSMS.GetEstado(out p),您无需初始化vMessages。但您需要使用其中一个关键字来调用 - obSMS.GetEstado(out vMessages)