您可以使用Convert.ToString((object)value)
. 您需要先将值转换为对象,否则转换将导致 null。
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 == "");
}
}
给出:
Convert.ToString(nullObject ) == null? False, == empty? True
Convert.ToString(nullString ) == null? True , == empty? False
Convert.ToString((object)nullString ) == null? False, == empty? True
如果将 System.DBNull.Value 传递给 Convert.ToString() ,它也会被转换为空字符串。