2013-03-08 183 views
0

使用对象初始化程序初始化对象时添加属性。但是我们如何添加DataCollection属性?使用对象初始化程序初始化对象时添加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
Student myStudent = new Student 
     { 
      FirstName = "John", 
      LastName = "Something" 
      Subjects = { 
          "Subject1", 
          "Subject2", 
          "Subject3", 
         } 
     }; 
+0

谢谢。它正在工作。 – SP007 2013-03-08 19:28:03

+0

@hellosuresh请将我的答案标记为接受,如果它解决了您的问题=) – 2013-03-08 19:33:57

+0

我们只能在一定的时间后回答。 – SP007 2013-03-08 19:35:02