Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[C#][RESOLVED] Using reflection to compare property names to objects in a list?


Mal
 Share

Recommended Posts

The idea behind what I'm wanting to do is for Project Old Beater to be completely open-ended in terms of what you can add, change, or remove from it. The way I've currently written the library for it is any item, class, or race can have an unlimited number of modifiers, but the player has a set number of attributes and additional properties that those modifiers line up with.

What I'm looking at trying to do, since it seems very unnecessary to nest a bunch of if/then/else statements and for/foreach loops is attempt to use reflection to compare the properties of the player class and other objects in that class to existing modifiers; when a comparison happens, the values of the modifiers are added or subtracted from that specific player property.

Having not done this myself (although I briefly looked into it) I'm wondering if anyone has much experience with reflection or other paradigms that would allow me to efficiently handle these things. Right now I'm looking at something like this:

```

// The classes involved, pseudo/truncated mockup

public class Player : GameAttributes

{

public string Name { get; set; }

}

public class GameAttributes

{

public int Health { get; set; }

public int Mana { get; set; }

public int Strength { get; set; }

public int Constitution { get; set; }

public int Dexterity { get; set; }

public int Willpower { get; set; }

public int Intellect { get; set; }

public int Awareness { get; set; }

}

```

Now a class (GameClass) has a modifier "Strength" with a value of positive 15\. Since we don't want to nest a lot of conditional statements and loops, so how would we go about doing that?

Edit: I figured it out.

```

Player plr = new Player();

plr.GetType().GetProperty("Health").SetValue(plr, 15);

```

Works like a charm.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...