在 C# 中,可以使用反射来实现从对象中找到某个字段并赋值为空。以下是一个示例代码:

using System;
using System.Reflection;

class MyClass
{
    public string MyField { get; set; }  
}

class Program
{
    static void Main(string[] args)
    {
        MyClass myObject = new MyClass();
        myObject.MyField = 'Hello World';

        Type type = typeof(MyClass);
        FieldInfo field = type.GetField('MyField', BindingFlags.Public | BindingFlags.Instance);

        if (field != null)
        {
            field.SetValue(myObject, null);
        }

        Console.WriteLine(myObject.MyField);  // 输出: null
    }
}

在上面的代码中,首先创建了一个MyClass对象,并给MyField字段赋了一个初始值。

然后使用typeof关键字获取MyClassType对象,并使用GetField方法通过字段名获取FieldInfo对象。

如果找到了对应的字段,就使用SetValue方法将字段的值设置为null

最后,可以验证字段的值是否为null。在上面的示例中,输出的结果是null

C# 使用反射将对象字段设置为 null

原文地址: https://www.cveoy.top/t/topic/qDvZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录