将构造函数的类成员和数据成员添加到c#中的列表中

时间:2015-07-22 12:21:00

标签: c#

我有这样的课程:

public class X
{
    public X()
    {
        Comments = new List<Y>();

    }

    [DataMember(Order = 0)]
    public string Key;

    [DataMember(Order = 1)]
    public List<Y> Comments;     
}

[DataContract]
public class Y
{
    [DataMember(Order = 0)]
    public string Body;

    [DataMember(Order = 1)]
    public string Author;
}

以下是我添加到列表的方式。

private List<X> Method(string result)
{
   List<X> ret = new List<X>
   List<X> temp = new List<X>
        { 
             new Y()
            {
                Body = Body,
                Author = Author
            },

            new X() {

            Key = issueKey,

            }  
        };
    ret.Add(temp);
    return ret;
  }

我做错了吗? 我收到错误:添加集合初始化程序有一些无效的参数,请建议如何解决此问题?

2 个答案:

答案 0 :(得分:1)

private List<X> Method(string result)
    {
        List<X> ret = new List<X>();
        X temp = new X
        {
            Comments = new List<Y>
            {
                new Y() { Author = "Author", Body = "Body" }
            },
            Key = "issueKey"
        };

        ret.Add(temp);
        return ret;
    }

答案 1 :(得分:0)

Y不是X,因此无法添加到List<X>