我知道java并且通常会放入getter/setter方法.我有兴趣使用以下代码在C#中执行此操作,但它会引发StackOverflow异常.我究竟做错了什么?
致电代码
c.firstName = "a";
Run Code Online (Sandbox Code Playgroud)
物业代码
public String firstName;
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
Run Code Online (Sandbox Code Playgroud) 如果我这样做,我得到一个System.StackOverflowException:
private string abc = "";
public string Abc
{
get
{
return Abc; // Note the mistaken capitalization
}
}
Run Code Online (Sandbox Code Playgroud)
我理解为什么 - 属性引用自身,导致无限循环.(在此处和此处查看以前的问题).
我想知道的(以及我之前没有看到的问题)是为什么C#编译器没有抓住这个错误?它检查一些其他类型的循环引用(继承自己的类等),对吗?只是这个错误不常见,值得检查吗?或者是否有一些我没有想到的情况,当你想要一个房产以这种方式实际引用自己的时候?
这很容易解释:这很有效
using System;
using ConstraintSet = System.Collections.Generic.Dictionary<System.String, double>;
namespace ConsoleApplication2
{
class test
{
public ConstraintSet a { get; set; }
public test()
{
a = new ConstraintSet();
}
static void Main(string[] args)
{
test abc = new test();
Console.WriteLine("done");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不
using System;
using ConstraintSet = System.Collections.Generic.Dictionary<System.String, double>;
namespace ConsoleApplication2
{
class test
{
public ConstraintSet a { get { return a; } set { a = value; } }
public test()
{
a = new ConstraintSet(); …Run Code Online (Sandbox Code Playgroud)