开发者

Dynamic array in C# (vb.net snippet)

Private Function getFoo(ByVal _FileInfo As FileInfo) As foo()
    Dim provider As New ExcelStorage(GetType(foo))
    provider.StartRow = 2
    provider.StartColumn = 1
    provider.FileName = _FileInfo.FullName
    Dim res() As foo = provider.ExtractRecords()
    Return res
End Function

I have the above code in vb.net that i'm trying to convert to C#. I'm using FileHelper library to extract data from Excel. This is my conversion to C#.

public static foo GetFoo(FileInfo fInfo)
{
var provider = new ExcelStorage(typeof(foo));
provider.StartRow = 2;
provider.StartColumn = 1;
provider.FileName = fInfo.FullName;
foo res[] = provider.ExtractRecords();
return res;
}

What am I doing wrong here. I'm getting Bad array declator. Do I have to declare the size the array first?

Thanks

edit: I change the code as suggested. However, I'm getting this error.

"Ca开发者_运维技巧nnot implicitly convert type 'object[]' to 'foo[]'. An explicit conversion exists (are you missing a cast?)"

I though I already set the type to foo in the ExcelStorage as typeof(foo). Nevermind, I did it with casting.


Should be: foo[] res = provider.ExtractRecords()


foo res[] = provider.ExtractRecords(); 

should be

foo[] res = provider.ExtractRecords(); 

Similarly, as you are returning an array of foos, the declaration should be:

public static foo[] GetFoo(FileInfo fInfo) 


In C# the array syntax is attached to the type and not the variable

foo[] res = provider.ExtractRecords();


In C#, you declare array variables like so Type[] VariableName not like this Type VariableName[]


It's foo[] res instead of foo res[].

In VB you can use either the syntax where being an array is a property of the variable:

Dim x() As Integer

or where being an array is a property of the type:

Dim x As Integer()

The former makes more sense in VB 6, where arrays are a special kind of varaibles, and the latter makes more sense in VB.NET where arrays are objects.

In C# being an array is always part of the type:

int[] x;


Plus your method needs to return an array as well

public static foo[] GetFoo(FileInfo fInfo)


Fixed code:

public static foo[] GetFoo(FileInfo fInfo)
{
  var provider = new ExcelStorage(typeof(foo));
  provider.StartRow = 2;
  provider.StartColumn = 1;
  provider.FileName = fInfo.FullName;
  foo[] res = provider.ExtractRecords();
  return res;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜