[英]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功能將其轉換為單行,並避免編寫所有這些命令性循環。
這就是說,當將源代碼從一種語言轉換為另一種語言時,不僅僅是簡單地搜索等效數據類型等等......您還可以利用目標語言提供的功能。
你可以用它替換它
List<string> macroSteps
用於類型安全的字符串列表 要么
ArrayList macroSteps
。 用於靈活的對象列表 要么
Stack<string> macroSteps
。 像JS一樣有.Push()
和.Pop()
。 它在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.