简体   繁体   中英

Converting VB code to C# using array and redim preserver keyword

This is my VB code:

If TxtStr(i) = "#" And TxtStr(i + 1) = "]" Then
    RefStr = RefStr & "]"
    ReDim Preserve RefStrLinks(1, RefStrLinkIndex)
    RefStrLinks(0, RefStrLinkIndex) = RefStr
    RefStr = RefStr.Replace("[#", String.Empty)
    RefStr = RefStr.Replace("#]", String.Empty)
    RefStrLinks(1, RefStrLinkIndex) = RefStr
    RefStrLinkIndex = RefStrLinkIndex + 1
    RefStr = String.Empty
    RefStrFound = False
End If

This is my converted code in C#; RefStrLinks is declared as:

string[,] RefStrLinks = null;

But this gives a compile error because of ReDim Preserve whenever I run this:

if (TxtStr[i].ToString() == "#" & TxtStr[i + 1].ToString() == "]")
{
    RefStr = RefStr + "]";
    Array.Resize<string>(ref RefStrLinks, RefStrLinkIndex + 1);
    RefStrLinks[0, RefStrLinkIndex] = RefStr;
    RefStr = RefStr.Replace("[#", string.Empty);
    RefStr = RefStr.Replace("#]", string.Empty);
    RefStrLinks(1, RefStrLinkIndex) = RefStr;
    RefStrLinkIndex = RefStrLinkIndex + 1;
    RefStr = string.Empty;
    RefStrFound = false;
}

Does anybody understand why?

Right; I think the real issue here is that you have a 2-dimensional array; RefStrLinks is not a string[] , but rather is a string[,] , with dimension 2 on the first axis. Array.Resize only works with vectors (a "vector" is a one-dimensional array with base index 0, ie string[] ).

Frankly, I would replace all of this (re-dimming an array or using Array.Resize per element is absurdly expensive) with something like:

List<SomeBasicType> list = ...
...
// where "foo" and "bar" are the two values that you intend to store per item
var item = new SomeBasicType(foo, bar);
list.Add(item);

where perhaps SomeBasicType is an immutable struct that takes two strings. Or more simply, in C# "current": value-type tuples:

// declare the list (change the names to something meaningful for your code)
var list = new List<(string name, string url)>();

// ... add values efficiently

string name = "whatever"; // your per-item code goes here
string url = "some value"; // and here
list.Add((name, url));

// ... show that we have the data

foreach(var item in list)
{
    Console.WriteLine($"{item.name} / {item.url}");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM