为什么C#编译器不停止属性引用自己? [英] Why doesn't the C# compiler stop properties from referring to themselves?

查看:169
本文介绍了为什么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
    }
}

我明白为什么 - 该属性引用自身,导致无限循环。 (见以前的问题此处 here )。

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?

推荐答案

p>您可以在最后一条评论中看到官方的原因 here

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


/ 2008 at
19:52

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

感谢您的建议
Visual Studio!

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

Alex Turner

项目经理

Visual C#编译器

Visual C# Compiler

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆