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);  // 异常
    }
}
相关推荐
njsgcs1 天前
拆分多实体到装配体 solidworks c#
c#
何以解忧唯有撸码1 天前
C# 视频录制监控系统
c#·winform
xiaoshuaishuai81 天前
C# modbustcp的ack包通信延迟原因
网络·tcp/ip·c#
hixiong1231 天前
使用C#自制一个截屏工具
c#
少控科技1 天前
小数典应用:小诗典
windows·c#
wuyoula2 天前
尹之盾企业版网络验证
服务器·开发语言·javascript·c++·人工智能·ui·c#
zdr尽职尽责2 天前
Untiy 处理Aseprite 资产 解决偏移问题
学习·unity·c#·游戏引擎
步步为营DotNet2 天前
.NET 11 与 C# 14 助力云原生应用安全架构升级
云原生·c#·.net
少控科技2 天前
小数典应用:农场环境数据采集监控
开发语言·windows·c#
¥-oriented2 天前
记录使用C#编程中遇到的一个小bug
c#·bug