VB 6.0中的String(33,0),C#中的等效项

问题描述 投票:4回答:4

在VB 6.0中UserName = String(33, 0)的含义是什么,在C#中是等效的。

[请帮助我在将VB 6.0代码转换为C#时遇到错误。

提前感谢。

c# vb6
4个回答
6
投票
String是一个函数,它返回包含指定长度的重复字符串的字符串。

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);


4
投票
在VB6中,该函数创建一个包含33个字符的字符串,这些字符的序号均为零。

通常,您这样做是因为您要将字符串传递给某个本机函数,该函数将填充缓冲区。在C#中,与此最接近的等效项是创建一个StringBuilder实例,然后将其通过p / invoke函数调用传递给本机代码。

我认为直接翻译一行代码不是特别有用。该代码存在于上下文中,我强烈怀疑该上下文很重要。

因此,尽管您可以使用33个空字符创建一个新的C#string,但这有什么意义呢?由于.net字符串是不可变的,因此您无法对此感兴趣。在您的VB6代码中,您肯定会对该对象进行突变,因此,我认为StringBuilder是最可能完成该工作的工具。


2
投票
我相信您正在寻找:

UserName = new String((Char)0, 33);

有关VB6方法的操作,请参考this

0
投票
您可以创建执行此操作的函数,或者o可以扩展类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; } }

© www.soinside.com 2019 - 2024. All rights reserved.