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);  // 异常
    }
}
相关推荐
唐青枫9 小时前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62513 小时前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021113 小时前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠1 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫3 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech4 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf5 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6255 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech6 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
2601_962072556 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos