从模型 class 更改 属性 的名称

Changing the name of a property from a model class

我想在某些情况下更改模型 class 中当前 属性 的名称。我正在阅读有关如何执行此操作和 运行 的可能解决方案,以解决我想做的事情。但是,当我使用 Reflection 执行以下操作时,它会显示

Object Reference not set to an instance of an object

但在模型中 class 我确实有这个名字。我没有正确使用它吗?

Model class:

public class Example1
 {

    public Property1 Property1 {get;set;}
 
 }

public class Property1
{
  public string Fruit {get; set;}
 
}

那么我有以下

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);
 }

我似乎不明白,如果我确实有 属性 名称,为什么它会给我那条消息。最后,我想将 属性 的名称从 Fruit 更改为 Car。任何指针将不胜感激。

你应该在 属性 内开始

Example1 myProperties = new Example1 { Property1=new Property1 { } };

您需要将对象 myProperties.Property1 作为方法的第一个参数传递 SetPropertyValue:

SetPropertyValue(myProperties.Property1, nameof(myProperties.Property1.Fruit), firstName);

您还需要实例化 属性 Property1:

Example1 myProperties = new();   
myProperties.Property1 = new();

这里已经为你解决了

var firstName = "Car";
Example1 obj = new();
obj.Property1 = new();
SetPropertyValue(obj.Property1, nameof(Example1.Property1.Fruit), firstName);