C# 检查对象是否为空 [英] C# Checking if Object is Null

查看:56
本文介绍了C# 检查对象是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 if 语句检查对象是否为空时遇到问题.

I am having trouble with an if statement for checking if an object is null.

我有一个 webClient 去尝试从网站中提取一个 JSON 字符串.如果出错,那是因为 API 中不存在 3 位国家,我只想跳过它.

I have a webClient go and pull a JSON string from a website in a try/catch. If it errors, it is because the 3 digit country does not exist in the API and I just want to skip it.

这是我的代码:

    System.Net.WebClient wc = new System.Net.WebClient();

    RootObject ro;
    try
    {
        string resp = wc.DownloadString("https://restcountries.eu/rest/v2/alpha/" + Row.Code.ToString());

        JavaScriptSerializer js = new JavaScriptSerializer();

        ro = js.Deserialize<RootObject>(resp);
    }
    catch (Exception e)
    { }

    if (ro.Region != null)
    {
        Row.Region = ro.Region;
        Row.SubRegion = ro.Subregion;
    }

RootObject 是一个要反序列化的类.这工作正常.

RootObject is a class to deserialize to. This works fine.

但是,我在 if 语句中收到一个错误,即使用未分配的类 'ro'.

However, I am getting an error in the if statement that "use of unassigned class 'ro'.

有人可以帮我解决这个问题吗?ro 在 if 内按预期工作?

Can someone help me fix this? ro works as expected inside the if?

我也试过检查一个特定的节点,但它仍然挂在ro"部分.

I have also tried checking a specific node and it is still getting hung up on the 'ro' part.

此外,这是 SSIS 中的脚本组件.

Also, this is a script component in SSIS.

谢谢

推荐答案

  1. try 块可能永远不会为 ro 赋值,因此它会在 try 块之外未分配.要解决这个问题,请分配一个值:

  1. It is possible that the try block will never assign a value to ro and thus it will be unassigned outside of try block. To fix that, assign a value:

RootObject ro = null;

  • 由于 ro 可能是 null,您需要在尝试访问成员之前在 if 语句中检查它:

  • Since ro could be null, you need to check for that in your if statement before you try to access a member:

    if (ro != null && ro.Region != null)
    {
        Row.Region = ro.Region;
        Row.SubRegion = ro.Subregion;
    }
    

  • 这篇关于C# 检查对象是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆