0

複雑なオブジェクトをリストに追加する構文を見つけようとしています。これが私が知っていることです:

ComplexObject temp = new ComplexObject() {attribute1 = 5, attribute2 = 6};
ComplexObjectList.Add(temp);

代わりに私がやりたいことは次のとおりです。

ComplexObjectList.Add(new ComplexObject(){attribute1 = 5, attribute2 = 6});

うまくいかないことはわかっていますが、事前にリストを作成せずにリストに追加する方法はありますか? この 1 つの関数呼び出し以外に temp は必要ありません。

4

2 に答える 2

3

Assume you have this class (main point being must be an accessible constructor and the properties you wish to set must be visible):

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

And you have this list:

var listOfPoint = new List<Point>();

Then you can, as your second example ponders, do this:

listOfPoint.Add(new Point { X = 13, Y = 7 });

Which is roughly (there are some slight differences, Eric Lippert has some good reads on this) equivalent to your first example:

var temp = new Point { X = 13, Y = 7 };
listOfPoint.Add(temp);

In fact, you could add the point at the time the list is constructed as well:

var listOfPoint = new List<Point>
    {
         new Point { X = 7, Y = 13 }
    };

Now the fact that you say you "realize that it doesn't work" is puzzling because your initializer syntax is correct, so I'm not sure if you're asking before trying it, or if there is an issue with the declaration of your list or your class that is throwing you off. That said, if your first code snippet compiled, technically so should your second.

于 2012-07-20T21:03:03.543 に答える
1

コードが機能するはずです。そうでない場合、問題はおそらく ComplexObjectList の宣言にあります。List<ComplexObject> ComplexObjectList = new List<ComplexObject>(); また、クラスのプロパティがパブリックであることを確認してください。

于 2012-07-20T21:01:29.207 に答える