![](/img/trans.png)
[英]A field initializer cannot reference the non-static field, method, or property
[英]Error 12 A field initializer cannot reference the non-static field, method, or property 'WindowsGame1.Player.BaseStrength
我不明白为什么它不会让我做以下事情。 有谁知道我可以做到这一点的方法?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsGame1
{
public class Player
{
int BaseStrength = 10;
int BaseIntelligence = 10;
int BaseDexterity = 10;
int BaseStamina = 10;
int BaseSpeed = 10;
int Damage;
int SpellDamage;
int Accuracy;
int LifePoints;
int CastingSpeed;
***int Damage = (BaseStrength / 2);***
}
}
我得到的错误是:
错误12字段初始值设定项无法引用非静态字段,方法或属性'WindowsGame1.Player.BaseStrength
如果您希望损坏是基于其他字段计算的值,则应使用属性 :
int Damage
{
get
{
return BaseStrength / 2;
}
}
另一方面,如果要在实例化对象时使用普通字段并将其设置一次,则应将初始化代码放在构造函数中。
public class Player
{
int baseStrength = 10;
int damage;
public Player()
{
damage = baseStrength / 2;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.