2011-01-30 79 views
0

我对C#和编程一般都很陌生,我遇到了错误(在标题框)当我运行此代码:帮助错误C#:非静态字段,方法或属性需要对象引用RpgTutorial.Character.Swordsmanship

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

      } 
     } 
    } 
} 

现在我知道我需要创建一个剑术的参考,但我该怎么做呢?感谢您的任何帮助!

回答

2

如果你试图访问该方法将被称为相同对象的Swordsmanship属性,那么您可以通过this参考访问:

if (this.Swordsmanship == 10) 
{ 
    ... 
} 
0

是一个HeroCharacter一个子类(或其他方式)?如果是这样,你可以参考物业Swordsmanship这样的:

if (this.Swordsmanship == 10) 
{ 
    ... 
} 

否则,如果你发现自己需要引用一个“英雄”,你可以在构造函数(和财产)添加到您的HeroSkills类是这样的:

public HeroSkills : Character 
{ 
    public Hero CurrentHero 
    { 
     get; 
     set; 
    } 

    public HeroSkills(Hero hero) 
    { 
     this.CurrentHero = hero; 
    } 
    ... 

注意,this关键字不是必需的,但表示您正在访问的属性是你的类的成员。这可以帮助您稍后阅读。然后,您可以参考CurrentHero在你的类的各种方法,如Skill()像这样:

if (this.CurrentHero.Swordsmanship == 10) 
{ 
    ... 
} 

你会在其他地方使用新修改的类在这样的代码:

Hero player1 = //some hero variable 
var skills = new HeroSkills(player1); 
int currentSkill = skills.Skill(); 
相关问题