0

メソッドに配列パラメーターを渡し、C# で動的配列を作成する方法を理解しようとしています。最後に2つ質問があります。


この LINQ to XML ステートメントはうまく機能しています。

XDocument doc = new XDocument(
    new XElement("Processes",
            from p in Process.GetProcesses()
            orderby p.ProcessName
            select (new XElement("Process", 
                        new XAttribute("Name", p.ProcessName), 
                        new XAttribute("PID", p.Id)))));

配列の受け渡しの概念を理解するために別の方法で書き直したいのですが、最後の行で InvalidOperationException が生成されます。

var query = from p in Process.GetProcesses()
            orderby p.ProcessName
            select p;

List<XElement> content = new List<XElement>();
foreach (var item in query)
{
    content.Add(new XElement("Process",
        new XAttribute("Name", item.ProcessName),
        new XAttribute("PID", item.Id)));
}

// Is there any other way to create dynamic array instead of using List 
// and converting it to Array?
var paramArr = content.ToArray();
XDocument doc = new XDocument(paramArr);

それについて 2 つの質問があります。

  1. このメソッドまたは同様のメソッドに配列パラメーターを渡すにはどうすればよいですか: public XDocument(params Object[] content)?

  2. リストを使用せずに C# で動的配列を作成し、配列にキャストする他の方法はありますか?

4

2 に答える 2

0

最初の質問については、この質問をご覧ください。 ドキュメントはこちらです。配列をオブジェクトにキャストすることで問題を解決できると思います:

XDocument doc = new XDocument((object)paramArr);

2 番目の質問: いいえ。C# の配列の長さは一定です。

于 2013-09-29T12:59:03.847 に答える