C#如何使类变量引用类中的另一个值

时间:2017-02-14 09:19:09

标签: 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变量的直接引用。

不能这样做吗?

4 个答案:

答案 0 :(得分: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(); }
}

答案 1 :(得分:3)

实施dateOfBirth的getter和setter以使用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 :(得分: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表达式读取readonly属性:

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

答案 3 :(得分: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;}
}
相关问题