c# - 为什么 C# 编译器不阻止属性引用自身?

标签 c# compiler-construction exception

如果我这样做,我会得到一个 System.StackOverflowException:

private string abc = "";
public string Abc
{
    get
    { 
        return Abc; // Note the mistaken capitalization
    }
}

我明白为什么——该属性正在引用自身,导致无限循环。 (参见前面的问题 herehere)。

我想知道的(以及我在之前的问题中没有看到的答案)是为什么 C# 编译器没有捕捉到这个错误?它会检查一些其他类型的循环引用(继承自自身的类等),对吗?仅仅是这个错误不够普遍,不值得检查吗?还是有一些我没有想到的情况,当您希望属性以这种方式实际引用自身时?

最佳答案

“官方”原因可以看最后评论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

关于c# - 为什么 C# 编译器不阻止属性引用自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2336847/

相关文章:

python - 在异常中向堆栈传递信息?

c# - WCF 服务和线程

c# - VS2012资源 "X"无法解析

c# - C# 将 MySQL 服务器上的表中的数据复制到本地 MySql 数据库表

c# - 异步执行存储过程而不等待它并阻塞 UI

c++ - "Undefined reference to"函数错误

java - 我自己的Java编译器和字节码: Problems invoking functions

java - JVM 是生成字节码还是运行字节码?

java - 在java中抛出规则

c++ - 如何构建捕获所有异常的 C++ Dll 包装器?