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

Why doesn#39;t the C# compiler stop properties from referring to themselves?(为什么 C# 编译器不阻止属性引用自己?)

本文介绍了为什么 C# 编译器不阻止属性引用自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I do this I get a System.StackOverflowException:

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

我明白为什么 - 属性引用自身,导致无限循环.(查看之前的问题这里和这里).

I understand why -- the property is referencing itself, leading to an infinite loop. (See previous questions here and here).

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

What I'm wondering (and what I didn't see answered in those previous questions) is why doesn't the C# compiler catch this mistake? It checks for some other kinds of circular reference (classes inheriting from themselves, etc.), right? Is it just that this mistake wasn't common enough to be worth checking for? Or is there some situation I'm not thinking of, when you'd want a property to actually reference itself in this way?

推荐答案

可以看官方"最后评论中的原因 这里.

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

Microsoft 于 2008 年 11 月 14 日发布于19:52

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.

亚历克斯·特纳

项目经理

Visual C# 编译器

Visual C# Compiler

这篇关于为什么 C# 编译器不阻止属性引用自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么 C# 编译器不阻止属性引用自己?