c# - 如何在 C#.NET 3.5 中检查对象是否为空?

标签 c# asp.net .net-3.5

如果对象包含 null 或空,那么如何验证或检查相同的条件?

如何bool检查对象objnull还是Empty

我的代码如下:

class Program
{
    static void Main(string[] args)
    {
        object obj = null;

        double d = Convert.ToDouble(string.IsNullOrEmpty(obj.ToString()) ? 0.0 : obj);
        Console.WriteLine(d.ToString());
    }
}

通过这段代码,我得到了 NullReference Exception 作为 Object reference not set to an instance of an object.

请帮忙。

这里我不会......

如何在不转换为 .ToString() 的情况下验证该对象是 null 还是 Empty ??

是否有检查相同的方法??

最佳答案

您遇到的问题是您的对象属于对象类型。为了使用 string.IsNullOrEmpty 对其进行评估,您应该将对象传递给 (string)

像这样:

static void Main(string[] args)
{
    object obj = null;

    double d = Convert.ToDouble(string.IsNullOrEmpty((string)obj) ? 0.0 : obj);
    Console.WriteLine(d.ToString());
}

这会很好地工作,因为您没有在您的(不存在的)对象上显式调用 .ToString。

关于c# - 如何在 C#.NET 3.5 中检查对象是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9323580/

相关文章:

c# - #Eval 短日期

c# - Morelinq exceptBy 使用几个特定元素

asp.net - 在 ASP.NET 中制作用户控件的最佳实践?

c# - Observable Arrays - 调用 Web 服务列出所有记录并将其绑定(bind)到表

c# - 无法将 DBNull.Value 转换为类型 'System.DateTime' 。请使用可空类型

asp.net - Cookie和子域

asp.net - Html 到 pdf 转换器

c# - Azure:检查外部服务器上新 json 文件的最佳方法

c# - 以编程方式使用 jira 的最佳方法

c# - WPF 数据网格 : converter and StringFormat