C# 通过字符串转换防止 Null 失败的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15835388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:07:07  来源:igfitidea点击:

best way to prevent Null failure with string casting

c#sqlstringparsingnull

提问by jth41

_callReportCode = reader["Call Report Code"].ToString();

I am attempting to handle the possibility for the object I am calling ToString on to be NULL. I am going to be using the above statement with several variables and I dont want to make an individual try/catch for each one... what is the best way to do null checking for strings.

我正在尝试处理我调用 ToString 的对象为 NULL 的可能性。我将使用带有多个变量的上述语句,我不想​​为每个变量单独尝试/捕获......对字符串进行空值检查的最佳方法是什么。

Other datatypes ive been doing this:

其他数据类型我一直在这样做:

int.TryParse(reader["Account Number"].ToString(), out _accountNumber);

In this code "reader" refers to a SqlDataReader but thats not really important for this question.

在这段代码中,“reader”指的是 SqlDataReader 但这对这个问题并不重要。

采纳答案by Bobson

Use the null-coalescing operator: ??

使用空合并运算符??

callReportCode = (reader["Call Report Code"] ?? "").ToString();

If the data in your field is DBNull.Value(rather than null), this will still work, because DBNull.Valueis not null, so the ??won't be used, and DBNull.Value.ToString()is "", which is what you'd want.

如果您的字段中的数据是DBNull.Value(而不是null),这仍然有效,因为DBNull.Valueis not null,因此??不会被使用,而DBNull.Value.ToString()is "",这正是您想要的。

回答by Clint

You can perform a check using String.IsNullOrEmpty()to ensure that it isn't going to be null, or you could write an extension method to perform some action if it's not null and another / nothing if it is.

您可以执行检查String.IsNullOrEmpty()以确保它不会为空,或者您可以编写一个扩展方法来执行某些操作,如果它不是空的,则另一个/什么都不是。

回答by eXecute

_callReportCode = Convert.ToString(reader["Call Report Code"]) should ensure there are no null there.

_callReportCode = Convert.ToString(reader["Call Report Code"]) 应该确保那里没有空值。

回答by Fabio Marcolini

you could create a method that you call when you want to make the check. This way you have to type the try catch only once... or you can create an extension method for string class to do this

您可以创建一个方法,在您想要进行检查时调用该方法。这样你只需要输入一次 try catch ......或者你可以为字符串类创建一个扩展方法来做到这一点

回答by dasblinkenlight

If your string is nullable, you need to check the value returned from the SqlDataReaderagainst DBNull.Value:

如果您的字符串可以为空,您需要检查从SqlDataReaderagainst返回的值DBNull.Value

_callReportCode = reader["Call Report Code"] as string;

If the object returned by reader["Call Report Code"]is nota string, it's DBNull.Value, so the ascast is going to set the value of _callReportCodeto nullas well.

如果返回的对象reader["Call Report Code"]不是一个string,它的DBNull.Value,所以as铸件要设置的值_callReportCodenull为好。

If you must set the string to a non-null in case the database value is missing, add ??, like this:

如果您必须将字符串设置为非空值以防数据库值丢失,请添加??,如下所示:

_callReportCode = (reader["Call Report Code"] as string) ?? string.Empty;

回答by Sanjeev Choudhary

Use following line of code:

使用以下代码行:

_callReportCode = String.IsNullorEmpty(reader["Call Report Code"]) ?
                  String.Empty :
                  reader["Call Report Code"].ToString();

instead of the following line:

而不是以下行:

_callReportCode = reader["Call Report Code"].ToString();

回答by Andre Calil

Convert.ToString(reader["Call Report Code"]);

It will return string.Emptyif the value is null.

string.Empty如果值为空,它将返回。

Source: http://msdn.microsoft.com/en-us/library/astxcyeh.aspx

来源:http: //msdn.microsoft.com/en-us/library/astxcyeh.aspx

Update: it also works with DBNull, I've just verified.

更新:它也适用于DBNull,我刚刚验证过。

Update 2: I decided to bring a more complete test here, just to be sure:

更新 2:我决定在这里进行更完整的测试,以确保:

DBNull dbNull = null;
DBNull dbNullEmpty = DBNull.Value;
string stringNull = null;
string stringEmpty = string.Empty;

var outcome1 = Convert.ToString(dbNull);//Empty string
var outcome2 = Convert.ToString(dbNullEmpty);//Empty string
var outcome3 = Convert.ToString(stringNull);//NULL
var outcome4 = Convert.ToString(stringEmpty);//Empty string

回答by Matthew

My suggestion is to never convert ToStringwhen the data isn't a string, and if the data is already a string, then calling ToStringis redundant, and a cast is all that's required.

我的建议是ToString当数据不是字符串时永远不要转换,如果数据已经是字符串,那么调用ToString是多余的,只需要一个强制转换。

I am making an assumption that the datatype in the database is integer, in which case, you can use a nullable int.

我假设数据库中的数据类型是整数,在这种情况下,您可以使用可为空的 int。

int? accountNumber = reader["Account Number"] == DBNull.Value ? null : (int?)reader["Account Number"];

I have made an extension method to do just this thing.

我已经做了一个扩展方法来做这件事。

public static class SqlDataReaderExtensions
{
    public static T Field<T>(this SqlDataReader reader, string columnName)
    {
        object obj = reader[columnName];

        if (obj == null)
        {
            throw new IndexOutOfRangeException(
                string.Format(
                    "reader does not contain column: {0}",
                    columnName
                )
            );
        }

        if (obj is DBNull)
        {
            obj = null;
        }

        return (T)obj;
    }
}

Usage

用法

int? accountType = reader.Field<int?>("Account Number"); // will return NULL or the account number.

回答by CADmageren

The easiest way I have found is

我发现的最简单的方法是

_callReportCode = reader["Call Report Code"] + "";

回答by Neo Vijay

i have some easiest and common Method.

我有一些最简单和常用的方法。

 public static string ToNULLString(this string Values)
        {
            if (string.IsNullOrEmpty(Values))
            {
                return "";
            }
            else
            {
                return Values.ToString();
            }
        }

use in C#

在 C# 中使用

string item = null;
string value = item.ToNULLString();