C#反射的NullReferenceException

背景

xml文件中有些元素的属性被删除,导致文件无法被读取(C#)。

调试之后发现,因为属性被删除,读进来会保持默认值null,在后续的反射中如果用这个null给字符串属性赋值,会抛异常。

另外发现前面还有其他一些属性也被删掉了,但并不会导致异常,只因它们的类型是int。

示例

csharp 复制代码
using System.Reflection;
class Program
{
    public int A
    {
        set;
        get;
    }

    public string B
    {
        set;
        get;
    }

    static void Main(string[] args)
    {
        Program program = new Program();
        PropertyInfo pa = program.GetType().GetProperty("A");
        pa.SetValue(program, null, null);  // 正常
        PropertyInfo pb = program.GetType().GetProperty("B");
        pb.SetValue(program, null, null);  // 异常
    }
}
相关推荐
阿松爱学习5 小时前
【Unity开发】Unity长截图功能实现
unity·c#·游戏引擎
_oP_i8 小时前
Windows 11 家庭中文版 25H2
c#
unicrom_深圳市由你创科技8 小时前
电池化成曲线MES追溯:关键点提取与验证
c#
老王IT8 小时前
C#语言基础语法介绍
开发语言·c#
人丰9 小时前
一次生产卡顿复盘:BI 数据抽取引发 PostgreSQL 长事务事故
数据库·c#
淡海水11 小时前
07-01-源码-.NET Core GC总览与架构
unity·架构·c#·.netcore·gc
weixin_4166600713 小时前
Mermaid流程图导出到Word:SVG、PNG与清晰度如何选择?
开发语言·c#
公子小六15 小时前
基于.NET的Windows窗体编程之WinForms自定义控件(3)
windows·c#·.net·音视频·winforms
光泽雨1 天前
动画生命周期
c#·wpf
波力海苔夹心脆6752 天前
C# StringBuilder 详解:字符串拼接为什么总说要用它?
开发语言·笔记·c#·.net·字符串·stringbuilder·入门教程