比较C#字符串对象 [英] Compare string and object in c#

查看:113
本文介绍了比较C#字符串对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅此code:

object x = "mehdi emrani";
string y = "mehdi emrani";
Console.WriteLine(y == x);

以上code返回真正

但是,这code:

object x = "mehdi emrani";
string y = "mehdi ";
y += "emrani";
Console.WriteLine(y == x);

以上code返回

所以,当第一code比较字符串对象,我得到真正

So when compare string and object in first code i get true.

但与第二code相比,我得到

But when compare with second code i get false.

这两个字符串是相同的,但为什么当我追加到该字符串,我的结果返回

Both string are same but why when i append to the string , my result returns false?

推荐答案

在各情况下, == X ,这类型的对象。这意味着你正在使用的正常参考值相等运算符。

In each case, the second operand of == is x, which is of type object. That means you're using the normal reference equality operator.

现在在第一种情况下,你使用两个字符串的常量的内容相同。 C#编译器将使用一个对象这两个引用。在第二种情况下, X 指具有相同内容不同的字符串对象。两个引用会有所不同,因此 == 将返回false。

Now in your first case, you're using two string constants with the same contents. The C# compiler will use a single object for those two references. In the second case, x and y refer to distinct string objects with the same contents. The two references will be different, so == will return false.

您可以修复的比较:


  • 使用等于代替 - 这是的重写的由字符串(相在 == 运营商这是唯一的重载的:

  • Use Equals instead - that's overridden by string (as opposed to the == operator which is only overloaded:

Console.WriteLine(y.Equals(x)); // or x.Equals(y), or Equals(y, x)

使用静态的等号(对象,对象)方法可以是有用的,如果其中一个参数可以为null;这意味着你不必担心的NullReferenceException

The use of the static Equals(object, object) method can be useful if either of the arguments can be null; it means you don't need to worry about a NullReferenceException.

请类型的两个变量字符串,此时中== 超载字符串将在编译时采摘,而超载字符串的内容进行比较,而不仅仅是引用

Make both variables of type string, at which point the == overload within string will be picked at compile-time, and that overload compares the contents of the strings, not just the references

这是值得注意的是,它不只是一个字符串文字本身由C#编译器被人注意的事情 - 这是关于编译时常EX pressions。因此,例如:

It's worth noting that it's not just a matter of the string literals itself being noticed by the C# compiler - it's about compile-time constant expressions. So for example:

object x = "mehdi emrani";
string y = "mehdi " + "emrani";
Console.WriteLine(y == x); // True

下面使用两个字符串其中的初始化不是的一样用来初始化 X一,但字符串连接是由编译器,实现了它,它已经用于 X 相同的字符串进行的。

Here y is initialized using two string literals which aren't the same as the one used to initialize x, but the string concatenation is performed by the compiler, which realizes it's the same string it's already used for x.

这篇关于比较C#字符串对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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