为什么会出现一个字符串添加空的时候也不例外? [英] Why is there no exception when adding null to a string?

查看:157
本文介绍了为什么会出现一个字符串添加空的时候也不例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么犯规此抛出一个异常不明白,obj为null

  obj对象= NULL; 
Console.WriteLine(Hello World的OBJ +);


解决方案

这编译成

  Console.WriteLine(String.Concat(Hello World的,则obj)); 



String.Concat 方法忽略参数。



它的定义是这样的:(从.NET参考源)

 公共静态字符串连接(对象为arg0,ARG1对象){
如果(arg0中== NULL){
为arg0 =的String.Empty;
}

如果(ARG1 == NULL){
ARG1 =的String.Empty;
}
返回CONCAT(arg0.ToString(),arg1.ToString());
}



我不知道为什么它不是简单地返回 arg1.ToString()如果将arg0 == NULL



String.Concat(字符串,字符串)方法是这样定义的:

 公共静态字符串连接(字符串STR0,字符串STR1){
如果(IsNullOrEmpty(STR0)){
如果(IsNullOrEmpty(STR1)){
返回的String.Empty;
}
返回STR1;
}

如果(IsNullOrEmpty(STR1)){
返回STR0;
}

INT str0Length = str0.Length;

字符串结果= FastAllocateString(str0Length + str1.Length);

FillStringChecked(结果为0,STR0);
FillStringChecked(结果,str0Length,STR1);

返回结果;
}


Why doesnt this throw an exception dont understand, obj is null

object obj = null;
Console.WriteLine("Hello World " + obj);

解决方案

This compiles to

Console.WriteLine(String.Concat("Hello World ", obj));

The String.Concat method ignores null parameters.

It's defined like this: (From the .Net reference source)

    public static String Concat(Object arg0, Object arg1) {
        if (arg0==null) {
            arg0 = String.Empty; 
        }

        if (arg1==null) { 
            arg1 = String.Empty;
        } 
        return Concat(arg0.ToString(), arg1.ToString());
    }

I don't know why it doesn't simply return arg1.ToString() if arg0==null.

The String.Concat(string, string) method is defined like this:

    public static String Concat(String str0, String str1) { 
        if (IsNullOrEmpty(str0)) { 
            if (IsNullOrEmpty(str1)) {
                return String.Empty; 
            }
            return str1;
        }

        if (IsNullOrEmpty(str1)) {
            return str0; 
        } 

        int str0Length = str0.Length; 

        String result = FastAllocateString(str0Length + str1.Length);

        FillStringChecked(result, 0,        str0); 
        FillStringChecked(result, str0Length, str1);

        return result; 
    }

这篇关于为什么会出现一个字符串添加空的时候也不例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆