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

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

问题描述

如果我这样做,我会收到 System.StackOverflowException

  private string abc =; 
public string Abc
{
get
{
return Abc; //注意错误的大写
}
}

该属性引用自身,导致无限循环。 (请参阅之前的问题此处这里)。



'm想知道(和我没有看到在以前的问题中回答)是为什么C#编译器抓住这个错误?它检查一些其他种类的循环引用(从自己继承的类,等等),对吧?只是这个错误不够常见,值得检查吗?或者是有一些我不在想的情况,当你想要一个属性实际上以这种方式引用自己?

解决方案

您可以在上一条评论中看到官方原因此处


11/2008 at
19:52



感谢您对
Visual Studio的建议!



你是对的,我们可以很容易地检测属性递归,但是我们
不能保证没有什么
可以通过
递归完成。属性
的主体可以设置对象
上的其他字段,这改变了下一个
递归的行为,可以根据用户从控制台输入的行为改变其行为

或甚至可以基于随机值的
表现不同。在这些情况下,
自递归属性确实可以
终止递归,但是我们有
无法确定在编译时是否为
(不解决
暂停问题!)



由于上述原因(和
断开更改,将需要
禁止)

Alex Turner



计划经理



Visual C#编译器



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).

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.

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#编译器不让属性引用它们自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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