2

How do I get a list of all the variables in a class, to be used in another class to indicate which Variables will and can be changed by it for example. This is mainly for not having to rewrite a enum when some variables are changed or added.

Edit: I want to create a class that has some stats that can be modified (Main), and another type of class (ModifyingObject) that has a list of all the stats that it can change and by how much. I want to easily get the variables of the main class, and add a list of which variables does the modifying class change. if I have let's say 10 variables for different stats how can I easily list all the stats the ModifyingObject class can change in the Main class.

public class Main{

   float SomeStat = 0;
   string SomeName = "name";

   List<ModifyingObject> objects;

   bool CanModifyStatInThisClas(ModifyingObject object){
      //check if the custom object can modify stats in this class
   }

}

public class ModifyingObject{
  ....
}
Simeon
  • 25
  • 1
  • 1
  • 5
  • you should probably show a coded example of what you have tried or what you are attempting to try.. something like this I have the feeling will get closed because you are not being more specific as to what your true needs are.. are you also wanting to use `Reflection`? or `BindingFlag` – MethodMan Apr 10 '13 at 21:00
  • You might want to consider using another data structure or a design pattern if you want to have a "dynamic" enum. But for us to help you, you'll need to be more specific with what you're attempting to do. – Spoike Apr 10 '13 at 21:06
  • Can you explain what you mean by *custom object* and *representative class*. All these words are so overloaded that they're easily misinterpreted. – Conrad Frix Apr 10 '13 at 21:24

1 Answers1

6

You can use reflection.

Example:

class Foo {
    public int A {get;set;}
    public string B {get;set;}
}

...

Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
    Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}

From here: How to get the list of properties of a class?

Properties have attributes (properties) CanRead and CanWrite, which you may be interested in.

Documentation: http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx

Your question is a little vague, though. This may not be the best solution... depends heavily on what you're doing.

Community
  • 1
  • 1
tnw
  • 13,521
  • 15
  • 70
  • 111
  • doing an Upgrade system in unity. And i have lots of items that change a classes stats. Some may not even change one stat and others may change them all. – Simeon Apr 10 '13 at 21:10
  • @Simeon I'm confused by your comment. Was this answer helpful or were you looking for something else? – tnw Apr 11 '13 at 12:47
  • yes it was with this i can write universal upgrades that work with any class for example that has the name property and it will change that. – Simeon Apr 11 '13 at 13:26