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);  // 异常
    }
}
相关推荐
lzhdim15 小时前
C# 中读取CPU、硬盘和内存温度
开发语言·c#
WarPigs15 小时前
.NET项目app.Config笔记
c#·.net
weixin_428005301 天前
C#调用 AI学习从0开始-第3阶段RAG向量数据库-文档切分与入库第15天
人工智能·学习·c#·向量数据库·rag·qdrant·文档切分与入库
心平气和量大福大1 天前
C#-WPF-布局-Grid
c#·wpf·visual studio
TeamDev1 天前
JxBrowser 9.3.1 版本发布啦!
java·前端·javascript·c#·混合应用·jxbrowser·浏览器控件
格林威1 天前
工业相机Chunk功能全解析:图像嵌入时间戳、编码器元数据(附堡盟C#代码)
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
Vae_Mars1 天前
C#中多线程异步操作的方法-Parallel.ForEachAsync
开发语言·c#·php
Arbori_262151 天前
Rider 调试 VisionMaster C# 用户脚本
c#·visionmaster
暗暗别做白日梦2 天前
Pulsar 消息同步机制
c#·linq