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);  // 异常
    }
}
相关推荐
WarPigs20 小时前
C# dll笔记
c#
淡笑沐白20 小时前
C# HttpClient完整使用指南
c#·httpclient
JaydenAI21 小时前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
小满Autumn21 小时前
MVVM Light 架构笔记:定位器、命令、消息与 IoC 实践
笔记·学习·架构·c#·上位机·mvvm
小满Autumn1 天前
CommunityToolkit.Mvvm 架构笔记:现代 MVVM、源生成器与工程化实践
笔记·架构·c#·.net·wpf·mvvm
加号31 天前
【C#】 JSON 序列化与反序列化:从入门到最佳实践
c#·json
胖纸不争1 天前
自建 Copilot Cli 代理:让 GitHub Copilot 真正"Bring Your Own Key"
ai·c#
FuckPatience1 天前
C# new List<T>(IEnumerable<T> collection),链表初始化时传入已存在链表
链表·c#·list
专注VB编程开发20年1 天前
工控上位机开发为什么固死.net 4.5.2sdk?适配win7
python·信息可视化·c#
狂人开飞机1 天前
18. 中介者模式(Mediator Pattern)
设计模式·c#·中介者模式