20

这有效:

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");
        }
    }
}

这不会:

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();
        }
        static void Main(string[] args)
        {
            test abc = new test();
            Console.WriteLine("done");
        }
    }
}

我在二等舱的 a 的 setter 上遇到堆栈溢出异常,我不知道为什么。我不能使用第一种形式,因为Unity 游戏引擎不支持它。

4

4 回答 4

47

当您编写 时a = value,您将再次调用属性设置器。

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

ConstraintSet a;
public ConstraintSet A { get { return a; } set { a = value; } }
于 2010-07-18T15:42:56.823 回答
20

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

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

当然,我通常会有一个更传统的名称 - 这意味着您可以在没有“值”位的情况下逃脱:

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

为了更详细地说明您当前的第二种形式为何抛出 a 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;
}
于 2010-07-18T15:42:58.407 回答
5

您不能在 getter 和 setter 中使用相同的变量名。这将导致它调用自己并最终导致堆栈溢出。太多的递归。

您需要一个支持变量:

private ConstraintSet _a;
public ConstraintSet a { get { return _a; } set { _a = value; } }
于 2010-07-18T15:44:31.193 回答
3

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

private ConstraintSet _a;
public ConstraintSet a { get { return _a; } set { _a = value; } }
于 2010-07-18T15:43:20.510 回答