开发者

Help With Error C#: An object reference is required for the non-static field, method, or property RpgTutorial.Character.Swordsmanship

I am very new to C# and programming in genera开发者_JAVA百科l and I'm having the error (described in the title box) when I run this code:

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

            }
        }
    }
}

Now I know I need to create a reference to Swordsmanship, but how exactly would I do that? Thank you for any help!


If you're trying to access the Swordsmanship property of the same object that the method would be called for, then you can access it via the this reference:

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


Is a Hero a subclass of Character (or the other way around)? If so, you can reference the property Swordsmanship like this:

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

Otherwise if you are finding yourself needing to reference a 'hero', you can add a constructor (and property) to your HeroSkills class like this:

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

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

Note that the this keyword is not required, but signifies that the property you are accessing is a member of your class. This can help you in readability later on. You can then reference the CurrentHero around your class in your various methods like the Skill() as so:

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

You would use your newly modified class elsewhere in code like this:

Hero player1 = //some hero variable
var skills = new HeroSkills(player1);
int currentSkill = skills.Skill();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜