2010-09-19 79 views
4

我想这个代码在转换为C#,想知道什么是等同于JavaScript的“的Array.push”? 下面的代码我正在转换的几行:C#相当于为Javascript“推”

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 
     } 
    } 

回答

9

你可以使用一个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功能优势,将其转化成一个班轮和避免编写所有必要的循环。

这是说,从一种语言转换的源代码到另一个时,它不是简单地寻找等价数据类型,等等问题......你也可以好好利用一下目标语言所提供的。

3

您可以替换或者与

  • List<string> macroSteps的类型安全列表的字符串

  • ArrayList macroSteps。一个灵活的对象列表中,
+0

并使用.Add你在哪里, d使用推() – 2010-09-19 11:51:34

1

它可以更干净,声明和在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世界中可能会如此不自然和丑陋,并且您将不得不保持这种丑陋...我们不希望您处于这个位置:)

+0

+1的LINQ(尽管它可能超出OP的现有知识):记住,你可以使用'。选择(YourDoSomeStuff)的''代替。选择(X => YourDoSomeStuff(X))' – 2010-09-19 14:02:03

+0

是的,我记得。但是,如果你在LINQ是新的可能很难理解。选择(DoSomeStuff)实际上是一个方法组。 – 2010-09-20 10:41:47