在VB 6.0中UserName = String(33, 0)
的含义是什么,在C#中是等效的。
[请帮助我在将VB 6.0代码转换为C#时遇到错误。
提前感谢。
String(number,character)
示例:
strTest = String(5, "a") ' strTest = "aaaaa" strTest = String(5, 97) ' strTest = "aaaaa" (97 is the ASCII code for "a")
在这种情况下,String(33,0)
将返回包含33个空字符的字符串。C#中的等效项是
UserName = new String('\0', 33);
通常,您这样做是因为您要将字符串传递给某个本机函数,该函数将填充缓冲区。在C#中,与此最接近的等效项是创建一个StringBuilder
实例,然后将其通过p / invoke函数调用传递给本机代码。
我认为直接翻译一行代码不是特别有用。该代码存在于上下文中,我强烈怀疑该上下文很重要。
因此,尽管您可以使用33个空字符创建一个新的C#string
,但这有什么意义呢?由于.net字符串是不可变的,因此您无法对此感兴趣。在您的VB6代码中,您肯定会对该对象进行突变,因此,我认为StringBuilder
是最可能完成该工作的工具。
UserName = new String((Char)0, 33);
有关VB6方法的操作,请参考this。
String
。using System;
public class Program
{
public static void Main()
{
Console.WriteLine(strGen("01",3));
}
//param s is the string that you can generete and the n param is the how many times.
private static string strGen(String s, int n){
string r = string.Empty;
for (int x = 1; x <= n; x++)
r += string.Copy(s);
return r;
}
}