C# 4.0 错误C#的帮助:非静态字段、方法或属性RpgTutorial.Character.剑术需要对象引用
我对C#和一般编程非常陌生,在运行以下代码时出现了错误(在标题框中描述):C# 4.0 错误C#的帮助:非静态字段、方法或属性RpgTutorial.Character.剑术需要对象引用,c#-4.0,C# 4.0,我对C#和一般编程非常陌生,在运行以下代码时出现了错误(在标题框中描述): using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace RpgTutorial { public class HeroSkills : Character { public int Skill() {
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace RpgTutorial
{
public class HeroSkills : Character
{
public int Skill()
{
if (Hero.Swordsmanship = 10)
{
}
}
}
}
现在我知道我需要创造一个剑术的参考,但我到底要怎么做呢?谢谢你的帮助 如果您试图访问将调用该方法的同一对象的
剑术
属性,则可以通过此
引用访问该属性:
if (this.Swordsmanship == 10)
{
...
}
英雄是字符的子类吗?如果是这样,您可以像这样引用属性
剑术
:
if (this.Swordsmanship == 10)
{
...
}
public HeroSkills : Character
{
public Hero CurrentHero
{
get;
set;
}
public HeroSkills(Hero hero)
{
this.CurrentHero = hero;
}
...
Hero player1 = //some hero variable
var skills = new HeroSkills(player1);
int currentSkill = skills.Skill();
否则,如果您发现自己需要引用一个“英雄”,您可以向HeroSkills
类添加一个构造函数(和属性),如下所示:
if (this.Swordsmanship == 10)
{
...
}
public HeroSkills : Character
{
public Hero CurrentHero
{
get;
set;
}
public HeroSkills(Hero hero)
{
this.CurrentHero = hero;
}
...
Hero player1 = //some hero variable
var skills = new HeroSkills(player1);
int currentSkill = skills.Skill();
请注意,this
关键字不是必需的,但表示您正在访问的属性是类的成员。这可以帮助您以后提高可读性。然后,您可以使用各种方法(如Skill()
)在类周围引用CurrentHero
,如下所示:
if (this.CurrentHero.Swordsmanship == 10)
{
...
}
您可以在代码的其他地方使用新修改的类,如下所示:
if (this.Swordsmanship == 10)
{
...
}
public HeroSkills : Character
{
public Hero CurrentHero
{
get;
set;
}
public HeroSkills(Hero hero)
{
this.CurrentHero = hero;
}
...
Hero player1 = //some hero variable
var skills = new HeroSkills(player1);
int currentSkill = skills.Skill();