我需要将VB代码转换为c#
Do Until MarkerPos = 0 Or i > UBound(Values)
s = Replace(s, Token, Values(i), , 1)
i = i + 1;
MarkerPos = Strings.InStr(s, Token);
Loop
我将其转换为
do
{
s = Replace(s, Token, Values(i), , 1)
i = i + 1;
MarkerPos = Strings.InStr(s, Token);
} while(MarkerPos = 0 || i > UBound(Values));
是否正确,是否与c#中的 UBound 有任何相似之处。???
答案 0 :(得分:2)
您只需使用values.Length
即可返回C#数组中的项目数:
do
{
s = Replace(s, Token, Values(i), , 1)
i = i + 1;
MarkerPos = Strings.InStr(s, Token);
}
while(MarkerPos = 0 || i > Values.Length -1);
(您也可以将.Count()
用于任何其他可枚举类型)
编辑:
另外 - 我认为你的情况可能是错误的:
i < Values.Length -1
EDIT2:
你的逻辑应该是AND:
while(MarkerPos = 0 && i < Values.Length-1);
答案 1 :(得分:1)
如果您有10个项目的数组,Ubound
将返回10,Length
将返回11。
您可以使用.GetUpperBound(0)
或.Lenght-1
证明
using System;
using Microsoft.VisualBasic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var ar = new string[11];
Console.WriteLine(ar.GetUpperBound(0));
Console.WriteLine(ar.Length);
Console.WriteLine(Microsoft.VisualBasic.Information.UBound(ar));
Console.ReadKey();
}
}
}
所以在this answer
的帮助下这就是你需要的,我想
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "123412341234";
string Token = "2";
var Values = new string[] {"a","b", "c" };
int i = 0;
int MarkerPos;
do
{
s = ReplaceFirst(s, Token, Values[i]);
MarkerPos = s.IndexOf(Token);
i++;
} while(MarkerPos != -1 && i <= Values.GetUpperBound(0));
Console.WriteLine(s);
Console.ReadKey();
}
static string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
}
}
答案 2 :(得分:0)
正如'the_lotus'的评论中所提到的,最自然的等价循环是“while(!”循环:
while (!(MarkerPos == 0 || i > Values.GetUpperBound(0)))
{
s = ...
i = i + 1;
MarkerPos = (s.IndexOf(Token) + 1);
}
请注意,我遗漏了'Replace'等效项 - 您正在使用的VB'Replace'方法的版本没有直接等效,但您可以验证常规字符串'Replace'方法是否足够或不。
答案 3 :(得分:-1)
c#中无人参与。您可以使用Values.Length之类的值,其中Values是您的字符串数组。
答案 4 :(得分:-1)
你可以写:
do
{
...
} while(MarkerPos != 0 && i < Values.Length);
答案 5 :(得分:-1)
我多次使用此页面,反之亦然:Convert vb.net to c# or c# to vb.net - developerfusion.com
它还支持python和ruby。