C# 将空值转换为字符串的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12300744/
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
A function to convert null to string
提问by James Andrew Smith
I want to create a function to convert any null value e.g. from a database to an empty string.
I know there are methods such as if value != null ?? value : String.Emptybut is there a way to pass nullto a method e.g.
我想创建一个函数来转换任何空值,例如从数据库到空字符串。我知道有一些方法,例如 ifvalue != null ?? value : String.Empty但是有没有办法传递null给一个方法,例如
public string nullToString(string? value)
{
if(value == null) return empty;
return value
}
But I am not sure on the parameter syntax to do this..
但我不确定要执行此操作的参数语法。
I tried the above but it says not a nullable type.
我尝试了上面的方法,但它说不是可以为空的类型。
Thanks in advance.
提前致谢。
采纳答案by Gareth Wilson
static string NullToString( object Value )
{
// Value.ToString() allows for Value being DBNull, but will also convert int, double, etc.
return Value == null ? "" : Value.ToString();
// If this is not what you want then this form may suit you better, handles 'Null' and DBNull otherwise tries a straight cast
// which will throw if Value isn't actually a string object.
//return Value == null || Value == DBNull.Value ? "" : (string)Value;
}
回答by Shyju
public string nullToString(string value)
{
return value == null ?string.Empty: value;
}
回答by cadrell0
You can just use the null coalesce operator.
您可以只使用空合并运算符。
string result = value ?? "";
回答by Icarus
When you get a NULL value from a database, the value returned is DBNull.Value on which case, you can simply call .ToString()and it will return ""
当您从数据库中获取 NULL 值时,返回的值为 DBNull.Value 在这种情况下,您只需调用.ToString()它就会返回""
Example:
例子:
reader["Column"].ToString()
Gets you ""if the value returned is DBNull.Value
让你""如果返回的值是DBNull.Value
If the scenario is not always a database, then I'd go for an Extension method:
如果场景并不总是一个数据库,那么我会使用 Extension 方法:
public static class Extensions
{
public static string EmptyIfNull(this object value)
{
if (value == null)
return "";
return value.ToString();
}
}
Usage:
用法:
string someVar = null;
someVar.EmptyIfNull();
回答by Rafiqzzaman Liton
public string ToString(this string value)
{
if (value == null)
{
value = string.Empty;
}
else
{
return value.Trim();
}
}
回答by live-love
Convert.ToString(object)converts to string. If the object is null, Convert.ToStringconverts it to an empty string.
Convert.ToString(object)转换为字符串。如果对象是null,Convert.ToString则将其转换为空字符串。
Calling .ToString()on an object with a null value throws a System.NullReferenceException.
调用.ToString()具有空值的对象会抛出System.NullReferenceException.
EDIT:
编辑:
Two exceptions to the rules:
规则的两个例外:
1) ConvertToString(string)on a null string will always return null.
1)ConvertToString(string)在空字符串上将始终返回空值。
2) ToString(Nullable<T>)on a null value will return "" .
2)ToString(Nullable<T>)在空值上将返回 "" 。
Code Sample:
代码示例:
// 1) Objects:
object obj = null;
//string valX1 = obj.ToString(); // throws System.NullReferenceException !!!
string val1 = Convert.ToString(obj);
Console.WriteLine(val1 == ""); // True
Console.WriteLine(val1 == null); // False
// 2) Strings
String str = null;
//string valX2 = str.ToString(); // throws System.NullReferenceException !!!
string val2 = Convert.ToString(str);
Console.WriteLine(val2 == ""); // False
Console.WriteLine(val2 == null); // True
// 3) Nullable types:
long? num = null;
string val3 = num.ToString(); // ok, no error
Console.WriteLine(num == null); // True
Console.WriteLine(val3 == ""); // True
Console.WriteLine(val3 == null); // False
val3 = Convert.ToString(num);
Console.WriteLine(num == null); // True
Console.WriteLine(val3 == ""); // True
Console.WriteLine(val3 == null); // False
回答by Stephen Turner
You can use Convert.ToString((object)value). You need to cast your value to an object first, otherwise the conversion will result in a null.
您可以使用Convert.ToString((object)value). 您需要先将您的值转换为对象,否则转换将导致空值。
using System;
public class Program
{
public static void Main()
{
string format = " Convert.ToString({0,-20}) == null? {1,-5}, == empty? {2,-5}";
object nullObject = null;
string nullString = null;
string convertedString = Convert.ToString(nullObject);
Console.WriteLine(format, "nullObject", convertedString == null, convertedString == "");
convertedString = Convert.ToString(nullString);
Console.WriteLine(format, "nullString", convertedString == null, convertedString == "");
convertedString = Convert.ToString((object)nullString);
Console.WriteLine(format, "(object)nullString", convertedString == null, convertedString == "");
}
}
Gives:
给出:
Convert.ToString(nullObject ) == null? False, == empty? True
Convert.ToString(nullString ) == null? True , == empty? False
Convert.ToString((object)nullString ) == null? False, == empty? True
If you pass a System.DBNull.Value to Convert.ToString() it will be converted to an empty string too.
如果您将 System.DBNull.Value 传递给 Convert.ToString(),它也会被转换为空字符串。
回答by Trojaner
Its possible to make this even shorter with C# 6:
使用 C# 6 可以使这个更短:
public string NullToString(string Value)
{
return value?.ToString() ?? "";
}
回答by Rogerio Azevedo
Its an old topic, but there is a "elegant" way to do that...
这是一个古老的话题,但有一种“优雅”的方式来做到这一点......
static string NullToString( object Value )
{
return Value = Value ?? string.Empty;
}
回答by David Orbelian
It is possible to use the "?." (null conditional member access) with the "??" (null-coalescing operator) like this:
可以使用“?” (空条件成员访问)与“??” (空合并运算符)像这样:
public string EmptyIfNull(object value)
{
return value?.ToString() ?? string.Empty;
}
This method can also be written as an extension method for an object:
这个方法也可以写成一个对象的扩展方法:
public static class ObjectExtensions
{
public static string EmptyIfNull(this object value)
{
return value?.ToString() ?? string.Empty;
}
}
And you can write same methods using "=>" (lambda operator):
您可以使用“=>”(lambda 运算符)编写相同的方法:
public string EmptyIfNull(object value)
=> value?.ToString() ?? string.Empty;

