2011-09-16 16 views
1

...は、私はこのような単純なデモ・クラスを持っています

従業員

public class Employee 
     { 
      public string Name { get; set; } 
      public string Email { get; set; } 

     } 

1つの以上のクラスのAddressDetails

public class AddressDetails 
     { 
      public string Address1 { get; set; } 
      public string City { get; set; } 
      public string State { get; set; } 
     } 

1オブジェクトより多くのEmpAdd

public class EmpAdd 
     { 
      public ICollection<Employee> Employees { get; set; } 
      public ICollection<AddressDetails> AddressDetails { get; set; } 
     } 

K、私はこのようなクラスではいくつかの値。..

Employee newEmp = new Employee(); 
      newEmp.Email = "[email protected]"; 
      newEmp.Name = "Judy"; 

      AddressDetails newAddress = new AddressDetails(); 
      newAddress.Address1 = "UK"; 
      newAddress.City = "London"; 
      newAddress.State = "England"; 

を渡していたときに、すべてが...

を正常に動作しますが、私はEmpAddにこの2を追加しようとしていたときに、それは私にエラー「オブジェクト参照をしませ与えますインスタンスに設定された」...これは単なるダミーです助けてください..私は、私は同じ問題に直面していた7つの実体を持っている....

EmpAdd emp = new EmpAdd(); 
      emp.Employee.Add(newEmp); 
      emp.AddressDetails.Add(newAddress); 

答えて

1

ICollectionプロパティは決して初期化されません。インスタンス化するコンストラクタを作成する必要があります。自動プロパティは、プロパティの後ろにフィールドを実装しますが、それでも割り当てる必要があります。 私はあなたの財産を読み取り専用(セットを取り除く)作り、その背後に自分でフィールドを実装し、宣言で、それを初期化する提案:

private List<Employee> _employees = new List<Employee>(); 

public ICollection<Employee> Employees { 
    get 
    { 
     return _employees; 
    } 
} 
+0

これはちょうど素晴らしいものでした.... thx ... –

2

emp.Employeeとemp.AddressDetailsがインスタンス化されていません。

public class EmpAdd 
{ 
    public ICollection<Employee> Employees { get; set; } 
    public ICollection<AddressDetails> AddressDetails { get; set; } 
    public EmpAdd() 
    { 
     Employees = new List<Employee>(); 
     AddressDetails = new List<AddressDetails>(); 
    } 
} 
+0

あなたのクイックレスポンスに感謝しています... –

0

何@Adrian Iftodeが意味することはこれです:

EmpAdd emp = new EmpAdd(); 
     emp.Employee = newEmp; 
     emp.AddressDetails = newAddress; 
     emp.Employee.Add(newEmp); 
     emp.AddressDetails.Add(newAddress); 

これで解決します。
とにかく、@Menno van den Heuvelの提案に固執してください。

+0

あなたの提案は.... + 1 –

関連する問題