使用对象初始化程序初始化对象时添加DataCollection属性

时间:2013-03-08 19:18:51

标签: c# object constructor ctor-initializer

使用对象初始化程序初始化对象时添加属性。但是我们如何添加DataCollection属性呢?

示例:

class Student{
          public string FirstName{ get; set} ;
          public string LastName{ get; set};
          public DataCollection<string> Subjects{ get; set} ; 

}

 Student myStudent = new Student
        {
            FirstName = "John",
            LastName = "Something"
            //Subjects.AddRange()
        };

因此,如果我们想为“主题”添加属性,我们如何添加上述条件?

一般情况下我们可以这样做。

     Student clsStudent  = new Student();
     clsStudent.FirstName  = "Foo";
     clsStudent.LastName  = "other";
     clsStudent.Values.AddRange(new string[] { "c#" });

1 个答案:

答案 0 :(得分:1)

Student myStudent = new Student
        {
            FirstName = "John",
            LastName = "Something"
            Subjects = {
                           "Subject1",
                           "Subject2",
                           "Subject3",
                       }
        };