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

查看:148
本文介绍了为什么从指自己不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
    }
}

我明白为什么 - 属性正在引用本身,导致一个无限循环。 (见previous问题<一href=\"http://stackoverflow.com/questions/367192/new-to-c-why-does-property-set-throw-stackoverflow-exception\">here和<一个href=\"http://stackoverflow.com/questions/680765/stackoverflow-on-class-property-closed\">here).

我不知道(什么,我没有看到这些previous回答的问题)是为什么不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?

推荐答案

您可以看到官方的原因,在最后一个注释<一个href=\"http://connect.microsoft.com/VisualStudio/feedback/details/377005/c-compiler-should-throw-an-error-for-property-getters-calling-themselves\">here.

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

发布Microsoft在14/11/2008在
  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.

亚历克斯·特纳

项目经理

的Visual C#编译器

Visual C# Compiler

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

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