XML : Use string as argument for GetValue()


I have a class Player, and an instance of that class called player. Inside that class, I have an auto-property called Name.

I need to access the property Name from the instance. I already know of other ways to do this, but because of what I want this program to do, I need to do it via:

  var type= Type.GetType("GameSpace.Player")  var property = type.GetProperty("Name");  var propVal = property.GetValue(player);    Console.WriteLine(propVal);    

This code works perfectly fine. The issue here is that sometimes, I will need to change the name of the instance, which in this case is player. I thought of making a string to hold the name of the instance.

  string instanceName = "player";  enter code here  var type= Type.GetType("GameSpace.Player")  var property = type.GetProperty("Name");  var propVal = property.GetValue(instanceName);    Console.WriteLine(propVal);    

But this doesn't working, throwing the error that GetValue doesn't have an overload that allows a string value.

Is there a way to accomplish what I am asking for. I know that I can simply do Console.WriteLine(player.Name), but in this case that is not an options, mostly because the arguments (name of instance) are stored in an XML file.

No comments:

Post a Comment