为什么C#编译器不让属性引用它们自己

为什么C#编译器不让属性引用它们自己

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

问题描述

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

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

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



'm想知道(和我没有看到在以前的问题中回答)是为什么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.

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

08-22 12:13