How do I dynamically refer to incremental properties in C #?

I have properties called reel1, reel2, reel3 and reel4. How can I dynamically refer to these properties by simply passing an integer (1-4) to my method?

In particular, I am looking for how to get a link to an object without knowing the name of the object.

In Javascript, I would do:

temp = eval("reel" + tempInt); 

and temp will be equal to reel1, the object.

It may not seem like this simple concept in C #.

+6
javascript reflection c #
source share
5 answers

This is what is usually avoided in C #. There are other alternatives.

In doing so, you can use Reflection to get a property value like this:

 object temp = this.GetType().GetProperty("reel" + tempInt.ToString()).GetValue(this, null); 

A better alternative would be to use the Indexed Property in your class, which allows you to do this[tempInt] .

+6
source share

You can access the property value by a string containing the property name using PropertyInfo .

Example:

 PropertyInfo pinfo = this.GetType().GetProperty("reel" + i.ToString()); return (int)pinfo.GetValue(this, null); 
0
source share

Try this link Get the appropriate PropertyInfo object for this property, and then use GetValue, passing it the instance by which you want to evaluate the property

0
source share

This is one of the things you can get away with an interpreted language like javascript, which is very difficult in a compiled language like C #. It is best to use another way:

 switch(tempInt) { case 1: temp = reel1; break; case 2: temp = reel2; break; case 3: temp = reel3; break; } 
0
source share

Use InvokeMember with BindingFlags.GetProperty. You must have a reference to the owner object, and you must know the type of property you are trying to get.

 namespace Cheeso.Toys { public class Object1 { public int Value1 { get; set; } public int Value2 { get; set; } public Object2 Value3 { get; set; } } public class Object2 { public int Value1 { get; set; } public int Value2 { get; set; } public int Value3 { get; set; } public override String ToString() { return String.Format("Object2[{0},{1},{2}]", Value1, Value2, Value3); } } public class ReflectionInvokePropertyOnType { public static void Main(string[] args) { try { Object1 target = new Object1 { Value1 = 10, Value2 = 20, Value3 = new Object2 { Value1 = 100, Value2 = 200, Value3 = 300 } }; System.Type t= target.GetType(); String propertyName = "Value3"; Object2 child = (Object2) t.InvokeMember (propertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty, null, target, new object [] {}); Console.WriteLine("child: {0}", child); } catch (System.Exception exc1) { Console.WriteLine("Exception: {0}", exc1.ToString()); } } } } 
0
source share

All Articles