Why doesn't the C# compiler stop properties from referring to themselves?

后端 未结 6 2108
灰色年华
灰色年华 2020-12-05 17:38

If I do this I get a System.StackOverflowException:

private string abc = \"\";
public string Abc
{
    get
    { 
        return Abc; // Note th         


        
6条回答
  •  生来不讨喜
    2020-12-05 17:59

    First of all, you'll get a warning for unused variable abc.

    Second, there is nothing bad in teh recursion, provided that it's not endless recursion. For example, the code might adjust some inner variables and than call the same getter recursively. There is however for the compiler no easy way at all to prove that some recursion is endless or not (the task is at least NP). The compiler could catch some easy cases, but then the consumers would be surprised that the more complicated cases get through the compiler's checks.

提交回复
热议问题