I am wanting to change the name of the property that is currently in the model class for certain conditions. I was reading up on how to do this and ran into a possible solution for what I am wanting to do. However, when I do the following with Reflection it says
Object Reference not set to an instance of an object
But in the model class I do have the name. Am I not using this correctly?
Model class
:
public class Example1
{
public Property1 Property1 {get;set;}
}
public class Property1
{
public string Fruit {get; set;}
}
then I have the following
var firstName = "Car";
Example1 myProperties = new();
SetPropertyValue(myProperties, myProperties.Property1.Fruit, firstName);
....
public static void SetPropertyValue(object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName); // grabs the property name
property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
}
I do not seem to understand why it is giving me that message if I do have the property name there. Ultimately I am wanting to change the name of the property from Fruit to Car. Any pointers would be appreciated.
Aucun commentaire:
Enregistrer un commentaire