虽然其他答案可能有效,但我提出以下替代方案。
我这样做的主要原因是其他示例要求您实际上使代码看起来更复杂一些,很明显您正在寻找清理代码,并使分配看起来更简单。如果您要在应用程序的不同位置创建这些 TreeNode,此解决方案也将为您提供帮助(其他解决方案将要求您将分配代码复制并粘贴到您正在创建 TreeNode 数组的每个位置。
让你的分配代码更干净的成本,是将混乱转移到其他地方(但老实说并不是很混乱,因为它真的很简单)
首先,创建一个类来为您构建 TreeNode 数组
public static class TreeNodeBuilder
{
public static TreeNode[] FromStringArray(String[] array)
{
TreeNode[] returnValue = new TreeNode[array.Length];
for(int i = 0; i < array.Length; i++)
{
returnValue[i] = new TreeNode(array[i]);
}
return returnValue;
}
}
然后在您的分配代码中,您可以使用以下内容:
String[] animals = {"dog", "cat", "mouse"};
TreeNode[] animalNodes = TreeNodeBuilder.FromStringArray(animals);
结论
This (IMHO) is a better option than using LINQ as the other answers provide, mostly for code clarity, maintainability, and the separation you can achieve by putting all of this logic in a different file (a file like TreeNodeBuilder.cs
).
For what it is worth you could also use the LINQ code provided in the other answers inside the above FromStringArray
function (if you wanted to get the best of both worlds).
Anyways, my two cents :) Hope you find it helpful.