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);  // 异常
    }
}
相关推荐
农村小镇哥14 小时前
C#中的字符串格式化
服务器·开发语言·c#
czhc114007566318 小时前
719:StartPoint;Margin;ResourceDictionar;Component.model;lds;
c#
-银雾鸢尾-19 小时前
C#中的万物之父——Object类
开发语言·c#
水晶石NSIS专栏19 小时前
Geek_Studio - 安卓终端调试工作台
android·c#·apk签名·coloros主题
-银雾鸢尾-20 小时前
C#中的继承
开发语言·c#
吴可可1231 天前
C#AutoCAD二次开发打断多段线
c#
-银雾鸢尾-1 天前
里氏替换原则
开发语言·c#·里氏替换原则
-银雾鸢尾-2 天前
C#中的索引器
开发语言·c#
en.en..2 天前
冒泡排序与选择排序完整对比解析
开发语言·数据结构·算法·c#·排序算法
geovindu2 天前
CSharp: Decorator Pattern
开发语言·后端·c#·装饰器模式·结构型模式