在我的类中使用许多枚举时的Stackoverflow异常

Dar*_*und -2 c# stack-overflow enums

我有一些枚举声明,因为我不明原因导致StackOverflowException.

我有以下内容:

public enum PrimaryAttribute
{
    Strength,
    Agility,
    Intelligence
}

public enum Class
{
    Tank,
    Fighter,
    Sorcerer
}

public class Hero
{
    public PrimaryAttribute PrimaryAttribute { get; private set; }
    public Class Class 
    {
        get
        {
            return Class;
        }
        set
        {
            if (Class == Class.Tank)
            {
                PrimaryAttribute = PrimaryAttribute.Strength;
                IsBlocking = true;
            }
            else if (Class == Class.Fighter)
            {
                PrimaryAttribute = PrimaryAttribute.Agility;
                IsBlocking = false;
                IsDodging = true;
            }
            else if (Class == Class.Sorcerer)
            {
                PrimaryAttribute = PrimaryAttribute.Intelligence;
                IsBlocking = false;
                IsDodging = false;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的主要方法中,我调用此类并为Hero.Class赋值

Hero hero = new Hero();
hero.Class = Class.Fighter;
Run Code Online (Sandbox Code Playgroud)

此时,如果我运行它,我得到一个StackOverflowException,为什么?

基本上我只想根据英雄类给某些属性赋值.

Dav*_*vid 6

枚举不会导致堆栈溢出.但这会:

get
{
    return Class;
}
Run Code Online (Sandbox Code Playgroud)

你获得的Class回报Class.这是一个无限递归.

您可能希望将值存储在后备变量中:

private Class _class;
public Class Class
{
    get
    {
        return _class;
    }
    set
    {
        // your existing logic, but use the variable instead
    }
}
Run Code Online (Sandbox Code Playgroud)