【问题标题】:Why System.Convert(object value) returns String.Empty not NULL when the value is NULL为什么 System.Convert(object value) 在值为 NULL 时返回 String.Empty 而不是 NULL
【发布时间】:2015-05-29 22:28:31
【问题描述】:

我遇到了与System.Convert(Object value) 方法相关的问题,我的研究使我找到了documentation
我想知道the reasonsc# 团队做出这个决定的背后是什么,因为这对我来说没有任何意义。
从我的角度来看,最好返回“Null”,请注意这个例子:

static void Main(string[] args)
    {
        int? ID = null; 
        string result = Convert.ToString(ID);
        Console.WriteLine("{0} ,{1}",result ,result.Length);
        Console.ReadKey();
    }
//result would be "" and the result.Length=0

如您所见,IDnull,但 convert(ID) 不是 null,这听起来很奇怪!!
这是convert(object value)的源代码,我是从这个问题的answer中捡到的。

public static string ToString(Object value) {return ToString(value,null);}

public static string ToString(Object value, IFormatProvider provider) { 
    IConvertible ic = value as IConvertible; 
    if (ic != null)
        return ic.ToString(provider); 
    IFormattable formattable = value as IFormattable;
    if (formattable != null)
        return formattable.ToString(null, provider);
    return value == null? String.Empty: value.ToString();

请关注last line。我只是想知道这背后的rational 是什么。
提前谢谢。

编辑

ID.Tostring() 根本没用的情况太多了
例如:

public System.Web.Mvc.ActionResult MyAction(int? Id)
{
//This line of code dosent show "Id has no value" at all 
MyContetnt = (System.Convert.ToString(Id) ?? "Id has no value");

return Content(MyContetnt);
}

在此代码示例中,如果您通过此路径运行此 Mvc 示例:
http://localhost: portnumber/ControllerName/MyAction
我的意思是without using ID in the path 你在屏幕上看不到Nothing,因为ID 在这里是nullConvert.Tostring(ID) 的结果是System.Empty 或“”。

我的意思是在这种情况下,无法使用null-coalescing-operator 重构此代码,使用ID.tostring() 会引发nullrefrenceException,这没有用,也不是我的意图。我知道这很容易说:

MyContent = Id.HasValue ? Id.Value.ToString() : "Id has no value" 
// this line works fine;

但是假设convert.ToString(Null) 的结果是Null 那么第一个带有null-coalescing-operator 的代码将完美运行。

所以我很好奇这个想法背后的原因是什么,
Convert.tostring (object null) 的结果是string.empty 而不是null

【问题讨论】:

  • 您可以使用 .ToString() 这将引发错误object reference not set to an instance of an object
  • 在您的情况下,string result = (ID).ToString(); 将返回异常,即object reference not set to an instance of an object
  • 可能是因为 null 不是字符串,而作者认为 null 最接近的字符串表示形式是空字符串?

标签: c# .net oop


【解决方案1】:

您问题中的陈述不正确。 Convert.ToString(object value) 确实在值为 null 时返回 null。这个

int? ID = null;
Console.WriteLine(Convert.ToString(ID) == string.Empty);
Console.WriteLine(Convert.ToString(null) == null);
object box = ID;
Console.WriteLine(Convert.ToString(box) == string.Empty);

写成真真真。

http://ideone.com/jRsefy

在您的示例中,您没有传递null,而是传递了对Nullable 的引用,即null

从您链接到的文档中(我必须阅读两次):

value 的字符串表示形式,如果 value 是一个字符串,则为 String.Empty 值为 null 的对象。如果 value 为 null,则该方法返回 null。

注意:问题没有指定框架版本,所以我假设是 4.5。 显然行为从 4.0 更改为 4.5,因此问题的答案是:他们意识到这是一个坏主意并进行了更改。

【讨论】:

【解决方案2】:

所有Convert 方法都以这种方式工作。这是您首先使用它们的唯一原因。

例如,考虑Convert.ToInt32。如果你通过null,你将得到0。如果您不想这样,您可以改用int.Parse - 这将抛出null 值。

同样,Convert.ToString 是从任何值(包括null)中获取字符串的安全方法。如果你想null 抛出,你可以使用object.ToString()。你可能会争辩说default(string)null,而不是string.Empty,但null 在这个意义上不是一个安全的值——你不能进一步使用null,除非明确检查null。另一方面,string.Empty 仍然允许您连接,或询问长度,或IndexOf,或...

重点是Convert 类被防范null 值,而是回到默认值。这不是技术原因,而是为了让(某些方式)编程更容易。

【讨论】:

    【解决方案3】:
    return value == null? String.Empty: value.ToString();
    

    在您的情况下, value == null 所以结果将是 string.Empty。方法 ID.ToString() 也是一样的

    public override string ToString()
    {
      if (!this.HasValue)
        return ""; //return empty string when value is null
      else
        return this.value.ToString();
    }
    

    但是如果你想在 id 为 null 的时候返回 null,那就为此写一个扩展。

    public static class Extension {
        public static string ToStringWithChecking(this int? param) {
            if (!param.HasValue) {
                return null;// or throw exception here
            }
            return param.ToString();
        }
    }
    

    【讨论】:

    • 感谢您的努力,但我正在寻找一些技术原因或基于设计的此类决定原因。
    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 2018-11-28
    • 2016-12-28
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    相关资源
    最近更新 更多