System.StackOverflowException , when get set Properties are used?

前端 未结 3 2002
半阙折子戏
半阙折子戏 2021-01-01 19:45

An unhandled exception of type \'System.StackOverflowException\' occurred in wcfserviceLibrary.DLL

the code is show as follows.

[DataContract]
public         


        
3条回答
  •  走了就别回头了
    2021-01-01 20:30

    The issue is that, as Konamiman said, you are calling a property recursively.

    Let's say I have a string property "DesignationName".

    public string DesignationName
    {
      //Some getter to return some data
      //Some setter to set the data
    }
    

    What would you expect it to return? How about returning a hard-coded string _designationName;

    private string _designationName = "someName";
    public string DesignationName
    {
      get {return _designationName;}
      //Some setter to set the data
    }
    

    That works. But what would happen if I had it return itself,instead?

    public string DesignationName
    {
      get {return DesignatioName;}
      //Some setter to set the data
    }
    

    Well, it would keep calling DesignationName, which would keep calling itself again, which would again call DesignationName...and so on. All of this puts data on the stack, and goes on forever until is overruns the allocated space for the stack. Voila, a stackoverflow.

    The reason your last example works is because it is using what is called an 'autoproperty', a new feature to .NET 3.0. Basically, behind the scenes, it is creating backing fields for your properties so that this:

    public string DesignationName
    {
      get;
      set;
    }
    

    actually compiles to behave like this:

    private string _designationName = string.Empty;
    public string DesignationName
    {
      get { return _designationName; }
      set { _designationName = value; }
    }
    

提交回复
热议问题