2017-02-14 331 views
3

我有以下簡化的類:C#如何使類變量引用的類中的另一個值

public class Foo 
{ 
    public DateTime dateOfBirth {get; set;} 
    public Age age {get; set;} 
} 

Age如下:

Public class Age 
{ 
    public DateTime dateOfBirth {get; set;}  
    //..Calculate age here 
} 

現在,我想Foo.Age.dateOfBirth等於Foo.dateOfBirth自動例如當用戶進行以下操作時:

var Foo foo = new Foo(); 
foo.dateOfBirth = //..whatever 

請注意,這不能在構造函數中,因爲用戶可能不會在構造函數中設置Dob,並且這也不會涵蓋Dob更改的情況。

它需要是對dateOfBirth變量的直接引用。

不能做他?

+0

有趣。如果「年齡」是公開的,爲什麼你想要第二個'dateOfBirth'等於'age.dateOfBirth'?你不喜歡輸入長變量名? – JHBonarius

+0

@ J.H.Bonarius它只是爲了說明的目的。出生日期存儲在班級內的另一個變量中,我將使用它來設置出生日期並計算人員的年齡。年齡班級 – Alex

回答

3

您可以使用setter方法:

public class Foo 
{ 
    private DateTime _dateOfBirth; 

    public DateTime DateOfBirth 
    { 
     get { return _dateOfBirth; } 
     set { 
      _dateOfBirth = value; 
      if(Age != null) 
       Age.DateOfBirth = value; 
     } 
    } 

    public Age Age { get; set; } 
} 

如果您會使DateOfBirth屬性取決於Age屬性更容易,你可以使用C#6表達式只讀屬性:

public class Foo 
{ 
    public DateTime DateOfBirth => Age?.DateOfBirth ?? DateTime.MinValue; 
    public Age Age { get; set; } 
} 
+2

不錯的C#6示例 – JHBonarius

+1

此解決方案(較長的一個)允許設置'Age.DateOfBirth'並因此破壞一致性。不過,我喜歡短的一個。 – wkl

+0

@wkl:好點。 –

3

您應該將Foo中的setter與Age中的setter關聯起來。 試試這個:

public class Foo 
{ 
public DateTime dateOfBirth { 
    get { return Age.dateOfBirth; } 
    set { Age.dateOfBirth = value; } 
} 
public Age age {get; set;} 

public Foo() { Age = new Age(); } 
} 
3

實現getter和的dateOfBirth二傳手使用Age屬性。與大多數其他的答案,這一次將確保此屬性始終!= null和兩個DateOfBirth屬性始終是一致的:

public class Foo 
{ 
    public DateTime dateOfBirth 
    { 
     get{ return Age.dateOfBirth; } 
     set{ Age.dateOfBirth = value; } 
    } 

    private readonly Age _age = new Age(); 
    public Age Age { get{ return _age; } } 
} 
2

是的,它應該可以通過使用下面的代碼,

public class Foo 
{ 
    private DateTime _dateOfBirth; 

     public DateTime dateOfBirth 
     { 
     get 
     { 
      return _dateOfBirth; 
     } 
     set 
     { 
      _dateOfBirth = value; 
      this.Age.dateOfBirth = value; 
     } 
    } 
    public Age age {get; set;} 
} 
+1

該解決方案允許設置Age.DateOfBirth,從而打破一致性。 – wkl

相關問題