Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 错误C#的帮助:非静态字段、方法或属性RpgTutorial.Character.剑术需要对象引用_C# 4.0 - Fatal编程技术网

C# 4.0 错误C#的帮助:非静态字段、方法或属性RpgTutorial.Character.剑术需要对象引用

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() {

我对C#和一般编程非常陌生,在运行以下代码时出现了错误(在标题框中描述):

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();