繁体   English   中英

C#相当于Javascript“推”

[英]C# equivalent to Javascript “push”

我正在尝试将此代码转换为C#,并且想知道Javascript的“Array.push”等同于什么? 这是我正在转换的几行代码:

 var macroInit1, macroInit2;
    var macroSteps = new Array();
    var i, step;

    macroInit1 = "Random String";
    macroInit2 = "Random String two";
    macroSteps.push(macroInit1 + "another random string");
    macroSteps.push(macroInit2 + "The last random string");

for (i=0; i<10; i++)
{
   for (step = 0; step < macroSteps.length; step++)
   {
     // Do some stuff 
      }
   }

您可以使用List<string>

var macroInit1 = "Random String";
var macroInit2 = "Random String two";
var macroSteps = new List<string>();
macroSteps.Add(macroInit1 + "another random string");
macroSteps.Add(macroInit2 + "The last random string");
for (int i = 0; i < 10; i++)
{
    for (int step = 0; step < macroSteps.Count; step++)
    {

    }
}

当然,这段代码在C#中看起来非常难看。 根据您对这些字符串执行的操作,您可以利用C#中内置的LINQ功能将其转换为单行,并避免编写所有这些命令性循环。

这就是说,当将源代码从一种语言转换为另一种语言时,不仅仅是简单地搜索等效数据类型等等......您还可以利用目标语言提供的功能。

你可以用它替换它

要么

要么

它在C#中可以更干净,更具说服力和更好,例如:

//In .NET both lists and arraus implement IList interface, so we don't care what's behind
//A parameter is just a sequence, again, we just enumerate through
//and don't care if you put array or list or whatever, any enumerable
public static IList<string> GenerateMacroStuff(IEnumerable<string> macroInits) {
{
    return macroInits
                .Select(x => x + "some random string or function returns that") //your re-initialization
                .Select(x => YourDoSomeStuff(x)) //what you had in your foreach
                .ToArray();
}

它可以用于:

var myInits = new[] {"Some init value", "Some init value 2", "Another Value 3"};
var myMacroStuff = GetMacroStuff(myInits); //here is an array of what we need

顺便说一句,如果你只是描述你想要的东西,我们可以建议你如何正确而恰当地“做东西”的解决方案,不只是向我们展示一个代码,我们没有任何线索如何使用,并询问如何翻译它。 因为在.NET世界中字面翻译可能如此不自然和丑陋,你将不得不保持这种丑陋......我们不希望你处于这个位置:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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