更改 class 任何字段的方法

Method for changing any field of the class

我有一个 Set 方法,我想传递字段名称和新值,以便它可以更改任何字段。 喜欢:

Person a = new Person("Marco", 5);
a.Set("age", 6);

我的实现不起作用,如何解决?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;

namespace Project
{
    public class Person
    {
        string name;
        int age;

        public Person(string name1, int age1)
        {
            name = name1;
            age = age1;
        }
        public void Set(string field_name, string new_value)
        {
            Type obj = typeof(Person);
            obj.GetProperty(field_name).SetValue(null, new_value);
        }
    }
}

null替换为this以设置Person当前实例的属性的值:

obj.GetProperty(field_name).SetValue(this, new_value);

但由于您有非public 字段,您应该使用带有一些绑定标志的GetField

obj.GetField(field_name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
    .SetValue(this, new_value);

您可能还需要一种方法来 获取 值并将 new_value 的类型更改为 object

另请注意,像这样设置值而不是使用强类型属性,速度较慢且容易出错。根据您的要求,您可能需要考虑使用 Dictionary<TKey, TValue>.