我在“设置”属性下面的行为是什么?

arj*_* kr 1 c#

我试图创建简单的事件,下面是代码块,但它不起作用。当我尝试调试时,一旦我们创建Point对象,它就会在“ Set”属性上抛出“ StackOverFlowException”(甚至在我们分配值px = 10之前)。我做错了什么?

using System;

namespace Workshop
{

    public class Point
    {
        public int x
        {
            get { return x; }
            set
            {
                x = value;
                onPointeChanged();
            }
        }

        public int y
        {
            get { return y; }
            set
            {
                y = value;
                onPointeChanged();
            }
        }

        public event EventHandler pointchanged;

        private void onPointeChanged()
        {
            if (pointchanged != null)
                pointchanged(this, EventArgs.Empty);
        }

    }

    public class Program
    {

        public static void Main(String[] args)
        {
            Point p = new Point();
            p.pointchanged += HandleEvent;
            p.x = 10;
        }

        public static void HandleEvent(object obj, EventArgs sender)
        {
            Console.WriteLine("Event Raised");
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

V0l*_*dek 5

您将set无限期地调用该方法,直到用完堆栈内存为止。你在做什么

x = value;
Run Code Online (Sandbox Code Playgroud)

是您正在调用x属性的setter,后者又会x = value调用,因此它会调用自身,依此类推,以此类推,直到永远。

要解决此问题,请引入一个字段:

private int x;

public int X
{
    get => x;
    set
    {
         x = value;
         OnPointChanged();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是创建属性的正确方法,该属性后面get和/或带有自定义逻辑set。如果您没有OnPointChanged()逻辑,就可以做

public int X { get; set; }
Run Code Online (Sandbox Code Playgroud)

这将为您生成以下代码:

private int x;
public int X { get => x; set => x = value; }
Run Code Online (Sandbox Code Playgroud)