开发者

Visual C# Delegate Array

Okay. So what I want to do... I'm trying to store a list of status effects as delegates in an array. The statuses will act like the statuses in the pokemon games.. (Stun makes you lose a turn etc).

I have this so far...

public class Statuses : Chara{
        public static void para(){
            this.health -= 10;
        }
    }

     status[] statuses = new status[]{
开发者_运维知识库        new status(Statuses.para)
    };

It's complaining about this not being a static property, I was wondering how I should proceed.

Thanks heaps.


The compiler error you most likely are getting when compiling the Statuses class says it all: “Keyword 'this' is not valid in a static property, static method, or static field initializer”: You are not allowed to reference “this” in a static method. If your health variable is static you can do like this:

private static int health;
public static void para() 
{
    health -= 10; 
}

If health is not static you will get this compiler error “An object reference is required for the non-static field, method, or property 'Statuses.health'.

Another error is that your para is not a property but a method. Since the code you have posted are very out of context a number of different errors could be present at well.


The problem the compiler is complaining about is that you've marked the method Para as static. You're then trying to access the health property of the current instance using this, which doesn't make sense, given that the containing method is static.

You should read up on the static keyword and its usage.


I think what you wanted to do was to create a delegate that reduces the instance's health, along the lines of (assuming you have a type called pokemon, with a property health):

public class Statuses : Chara{
    public static Action<Pokemon> para =
        (pokemonInstance) => { pokemonInstance.Health -= 10; };
}

Action<Pokemon>[] statuses = new Action<Pokemon>[]{
    Statuses.para
};

Read up on Action<T> and Anonymous Methods.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜