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

后端 未结 6 2098
灰色年华
灰色年华 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:47

    You can see the "official" reason in the last comment here.

    Posted by Microsoft on 14/11/2008 at 19:52

    Thanks for the suggestion for Visual Studio!

    You are right that we could easily detect property recursion, but we can't guarantee that there is nothing useful being accomplished by the recursion. The body of the property could set other fields on your object which change the behavior of the next recursion, could change its behavior based on user input from the console, or could even behave differently based on random values. In these cases, a self-recursive property could indeed terminate the recursion, but we have no way to determine if that's the case at compile-time (without solving the halting problem!).

    For the reasons above (and the breaking change it would take to disallow this), we wouldn't be able to prohibit self-recursive properties.

    Alex Turner

    Program Manager

    Visual C# Compiler

提交回复
热议问题