我正在将一些属性读回到对象的构造函数中。其中一个属性是从另一个属性计算出来的。
但是当我创建这个对象时,计算出的Implementation_End_String
属性值始终为null:
private string implementationEndString;
public string Implementation_End_String {
get{
return implementationEndString;
}
set {
implementationEndString= DataTimeExtensions.NullableDateTimeToString(Implementation_End);
}
}
问题:
如何将计算属性传递给对象构造函数?
这是ctor和计算属性的要点:
private string implementationEndString;
public string Implementation_End_String {
get{
return implementationEndString;
}
set {
implementationEndString= DataTimeExtensions.NullableDateTimeToString(Implementation_End);
}
}
public DateTime? Implementation_End { get; set; }
public ReleaseStatus(DateTime? implementationEnd)
{
//value is assigned at runtime
Implementation_End = changeRequestPlannedImplementationEnd;
}
答案 0 :(得分:1)
这样写。
private string implementationEndString = DataTimeExtensions.NullableDateTimeToString(Implementation_End);
public string Implementation_End_String
{
get{ return implementationEndString; }
set{ implementationEndString=value; }
//if you don't want this property to be not changed, just remove the setter.
}
在获得属性值之后,它将采用DataTimeExtensions.NullableDateTimeToString(Implementation_End);
的值。在您的代码中,当您尝试获取实现返回null
时,因为implementationEndString是null
。
答案 1 :(得分:1)
不需要字段implementationEndString
。只需将Implementation_End_String
设为只读属性,并在需要时从其他属性创建字符串:
public string Implementation_End_String
{
get
{
return DataTimeExtensions.NullableDateTimeToString(Implementation_End);
}
}