Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于更改类的任何字段的方法_C#_.net_Oop_Setter - Fatal编程技术网

C# 用于更改类的任何字段的方法

C# 用于更改类的任何字段的方法,c#,.net,oop,setter,C#,.net,Oop,Setter,我有一个方法集,我想传递字段名和新值,以便它可以更改任何字段。 比如: 我的意识不起作用,如何修复 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Threading.Tasks; namespace Project { public class Person {

我有一个方法集,我想传递字段名和新值,以便它可以更改任何字段。 比如:

我的意识不起作用,如何修复

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);
但由于您有非公共字段,因此应使用带有一些绑定标志的
GetField

obj.GetField(field_name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
    .SetValue(this, new_value);
您可能还需要一种方法来获取值,并将
new\u value
的类型更改为
object


还请注意,像这样设置值,而不是使用强类型属性,速度较慢且容易出错。根据您的要求,您可能需要考虑使用<代码>字典< /> > .< /p> < p>替换<代码> null <代码> < <代码> > <代码>,设置当前代码的属性值>代码>人<代码>:

obj.GetProperty(field_name).SetValue(this, new_value);
但由于您有非公共字段,因此应使用带有一些绑定标志的
GetField

obj.GetField(field_name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
    .SetValue(this, new_value);
您可能还需要一种方法来获取值,并将
new\u value
的类型更改为
object


还请注意,像这样设置值,而不是使用强类型属性,速度较慢且容易出错。根据您的要求,您可能需要考虑使用<代码>词典< /> > ./p>用该字段替换NULL和GETField属性,同时字段也应该是公共的(或者您应该使用绑定标志),用这个替换NULL,用GETField获取属性,字段也应该是公共的(或者您应该正确绑定标志)。给出一个错误
未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例。
@Aska:请参阅我的编辑。给出一个错误
未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例。
@Aska:请参阅我的编辑。