lundi 6 juillet 2015

Why won't my reflection work? [duplicate]

This question already has an answer here:

I have the following method where I get an integer from the user, it's for a small text based game I'm making, I'm using OO though.

public int getInt(string information)
        {
            int num = 0;

            try
            {
                Console.WriteLine("What is your " + information + "?: ");
                num = int.Parse(Console.ReadLine());
                Console.WriteLine("Your " + information + " is: " + num);
            }
            catch
            {
                Console.WriteLine("Value: '" + num + "' was not a numerical character!");
            }

            setStats(information, num);

            return num;
        }

This works as intended.

However, my setStats method doesn't work as intended.

public void setStats(string nameofStat, int valueofStat)
        {

            PropertyInfo prop = stat.GetType().GetProperty(nameofStat);

            prop.SetValue(nameofStat, valueofStat, null);

            Console.WriteLine(stat.ToString());
        }

I'm using the reflection class because I don't want to do this for every new stat.

                if (nameofStat == "Agility")
                {
                   stat.agility = 1;
                }

The error I get is "Object reference not set to an instance of an object." because my prop instance is null, but I don't know why it's null.

on the line:

prop.SetValue(nameofStat, valueofStat, null);

Please help!





Aucun commentaire:

Enregistrer un commentaire