2016-10-14 51 views
0

我正在读回一些属性到对象的构造函数中。其中一个属性是对另一个属性的计算。如何添加分配计算的属性值到对象?

但是,当我创建这个对象计算Implementation_End_String属性值总是空:

private string implementationEndString; 
    public string Implementation_End_String { 
     get{ 
      return implementationEndString; 
     } 
     set { 

      implementationEndString= DataTimeExtensions.NullableDateTimeToString(Implementation_End); 
     } 
    } 

问:

你怎么可以在计算特性传递给对象的构造函数?

这是构造函数的依据和计算性能:

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

的[?什么是一个NullReferenceException,以及如何解决呢(可能的复制http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mybirthname

回答

1

不需要该字段implementationEndString。只是让Implementation_End_String一个只读属性,并在需要时创建从其他财产的字符串:

public string Implementation_End_String 
{ 
    get 
    { 
     return DataTimeExtensions.NullableDateTimeToString(Implementation_End); 
    } 
} 
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

+0

这给了一个编译器错误:“字段初始值设定项不能引用非静态字段,方法或属性。很明显,因为NullableDateTimeToString是一个静态方法。不知道在这种情况下要做什么。 –