c#setter中的堆栈溢出exception

这很容易解释:这很有效

using System; using ConstraintSet = System.Collections.Generic.Dictionary; 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"); } } } 

这不

 using System; using ConstraintSet = System.Collections.Generic.Dictionary; namespace ConsoleApplication2 { class test { public ConstraintSet a { get { return a; } set { a = value; } } public test() { a = new ConstraintSet(); } static void Main(string[] args) { test abc = new test(); Console.WriteLine("done"); } } } 

我在第二类的setter上得到了堆栈溢出exception,我不知道为什么。 我不能使用第一种forms,因为统一引擎不支持它

当你写a = value ,你再次调用属性setter。

要使用非自动属性,您需要创建一个单独的私有支持字段,如下所示:

 ConstraintSet a; public ConstraintSet A { get { return a; } set { a = value; } } 

你还没有声明一个支持变量 – 你刚刚得到了一个getter和setter自己调用的属性。 我不清楚为什么 Unity不支持第一种forms – 这意味着它可能也不会支持等效,但它基本上是这样的:

 private ConstraintSet aValue; public ConstraintSet a { get { return aValue; } set { aValue = value; } } 

当然,我通常会有一个更传统的名字 – 这意味着你可以在没有“价值”的情况下离开:

 private ConstraintSet constraints; public ConstraintSet Constraints { get { return constraints; } set { constraints = value; } } 

为了更详细地介绍当前第二种forms抛出StackOverflowException ,您应该始终记住属性基本上是伪装的方法。 你破碎的代码看起来像这样:

 public ConstraintSet get_a() { return get_a(); } public void set_a(ConstraintSet value) { set_a(value); } 

希望很明显为什么这个版本正在吹嘘堆栈。 修改后的版本只是设置一个变量而不是再次调用该属性,所以在展开时它看起来像这样:

 private ConstraintSet aValue; public ConstraintSet get_a() { return aValue; } public void set_a(ConstraintSet value) { aValue = value; } 

您需要在公共属性中使用私有支持变量:

 private ConstraintSet _a; public ConstraintSet a { get { return _a; } set { _a = value; } } 

您不能在getter和setter中使用相同的变量名。
这将导致它自己调用并最终将stackoverflow。 递归太多了。
你需要一个支持变量:

 private ConstraintSet _a; public ConstraintSet a { get { return _a; } set { _a = value; } }