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);  // 异常
    }
}
相关推荐
专注仿真4 小时前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类
我是苏苏6 小时前
Agent 开发实战 :C#实现语义检索!向量数据库Qdrant的下载安装及调试步骤
c#·ai编程
光泽雨7 小时前
IEnumerable<T> 详细讲解
c#·c
Lost of 程序猿7 小时前
.NET 10 船端单机部署与离线升级实战:从闪退事故到无感回滚
c#·asp.net·.net
淡海水8 小时前
11-04-Unity-Span-foreach-LINQ的分配与热路径边界
unity·c#·linq·foreach·span
唐青枫1 天前
对象到底住在哪里?C#.NET 托管堆从分配、GC 到内存排查
c#·.net
fogota1 天前
Emoji与Segoe MDL2 Assets的比较
c#·wpf
灸木1 天前
C# 多线程与异步
c#
鱼听禅1 天前
C# 学习笔记-使用 类型化客户端搭建HTTP客户端服务
学习·http·c#·工厂方法模式
geovindu1 天前
CSharp:Condition Variable Pattern
后端·设计模式·c#·.net·.netcore·条件变量模式·同步型模式