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);  // 异常
    }
}
相关推荐
专注VB编程开发20年7 小时前
AI 生成C# WinForm 窗体 = 目前就是垃圾
开发语言·人工智能·c#
z落落8 小时前
C# 泛型接口和泛型类+泛型约束
开发语言·c#
阿正的梦工坊8 小时前
【Rust】08-集合类型、字符串与迭代器入门
开发语言·rust·c#
FuckPatience8 小时前
C# 使用泛型协变将派生类类型替换为基类类型
开发语言·c#
guygg888 小时前
C# 生成中间带 Logo 头像的二维码
开发语言·c#
Java面试题总结9 小时前
C#12 中的 Using Alias
开发语言·windows·c#
加号39 小时前
【C#】 ASCII 码转字符串技术解析
开发语言·c#
2601_9618752410 小时前
高考真题word版下载|2025高考全科真题可编辑文档
c#·word·ar·vr·mr·高考·oneflow
阿正的梦工坊12 小时前
【Rust】09-泛型、Trait 与生命周期基础
开发语言·rust·c#
z落落12 小时前
C# 事件(Event)+自定义带参数事件例子
开发语言·分布式·c#