C#如何使类变量引用类中的另一个值
发布时间:2020-12-15 23:49:11 所属栏目:百科 来源:网络整理
导读:我有以下简化类: public class Foo{ public DateTime dateOfBirth {get; set;} public Age age {get; set;}} 和年龄如下: Public class Age{ public DateTime dateOfBirth {get; set;} //..Calculate age here} 现在,我希望Foo.Age.dateOfBirth自动等于Foo
我有以下简化类:
public class Foo { public DateTime dateOfBirth {get; set;} public Age age {get; set;} } 和年龄如下: 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变量的直接引用. 不能做他的事吗? 解决方法
你可以使用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表达式bodied readonly属性: public class Foo { public DateTime DateOfBirth => Age?.DateOfBirth ?? DateTime.MinValue; public Age Age { get; set; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |