在 class 中使用许多枚举时出现 Stackoverflow 异常
Stackoverflow exception when using many enumarations inside my class
我有一些枚举声明,出于未知原因导致 WhosebugException。
我有以下内容:
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;
}
}
}
}
在我的主要方法中,我调用此 class 并为 Hero.Class
赋值
Hero hero = new Hero();
hero.Class = Class.Fighter;
此时如果我 运行 我得到一个 WhosebugException,为什么?
基本上我只是想根据英雄给一些属性赋值class..
枚举不会导致堆栈溢出。但这将:
get
{
return Class;
}
你的 getter Class
returns Class
。这是一个无限递归。
您可能希望将值存储在后备变量中:
private Class _class;
public Class Class
{
get
{
return _class;
}
set
{
// your existing logic, but use the variable instead
}
}
我有一些枚举声明,出于未知原因导致 WhosebugException。
我有以下内容:
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;
}
}
}
}
在我的主要方法中,我调用此 class 并为 Hero.Class
赋值Hero hero = new Hero();
hero.Class = Class.Fighter;
此时如果我 运行 我得到一个 WhosebugException,为什么?
基本上我只是想根据英雄给一些属性赋值class..
枚举不会导致堆栈溢出。但这将:
get
{
return Class;
}
你的 getter Class
returns Class
。这是一个无限递归。
您可能希望将值存储在后备变量中:
private Class _class;
public Class Class
{
get
{
return _class;
}
set
{
// your existing logic, but use the variable instead
}
}