You could expand it to something like the following :
public class YourClass
{
public int Property1 { get; set; }
public int Property2 { get; set; }
public int Property3 { get; set; }
public int GetPropertyByInteger(int n)
{
// Build your property name here
var propertyName = String.Format("p{0}p", n);
return Convert.ToInt32(this.GetType().GetProperty(propertyName).GetValue(this, null));
}
}
which would allow you to reference your property by just passing in the index you needed :
var property3 = YourClass.GetPropertyByInteger(3);
Another solution would be to write a custom indexer that is similar to the above method (and still uses Reflection) and set it on your class :
public class YourClass
{
public int p1p { get; set; }
public int p2p { get; set; }
public int p3p { get; set; }
public int this[int n]
{
get
{
return Convert.ToInt32(this.GetType().GetProperty(String.Format("p{0}p",n)).GetValue(this, null));
}
}
}
which would allow you to reference your properties via :
// Access your class via a property name
int property1 = yourClass[1];
Member
297 Points
178 Posts
variable class property
Jun 27, 2014 01:55 PM|mylok|LINK
I have class1 with proporty p1p, p2p, p3p....p10001p...ect
now depend on pass parameter n (it is integer) I need to access class1.pnp
is there anyway to do that?
All-Star
114593 Points
18503 Posts
MVP
Re: variable class property
Jun 27, 2014 03:13 PM|Rion Williams|LINK
You may be able to access it via Reflection as mentioned in this similar Stack Overflow discussion :
You could expand it to something like the following :
which would allow you to reference your property by just passing in the index you needed :
Another solution would be to write a custom indexer that is similar to the above method (and still uses Reflection) and set it on your class :
which would allow you to reference your properties via :