c# - .Equals 和 == 有什么区别

标签 c# .net string

<分区>

对于值类型、引用类型和字符串,a.Equals(b)a == b 之间有什么区别?似乎 a == b 对字符串工作得很好,但我正在尝试确保使用良好的编码实践。

最佳答案

来自 When should I use Equals and when should I use == :

The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.

For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object.

Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.

using System;

public class Test
{
    static void Main()
    {
        // Create two equal but distinct strings
        string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
        string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});

        Console.WriteLine (a==b);
        Console.WriteLine (a.Equals(b));

        // Now let's see what happens with the same tests but
        // with variables of type object
        object c = a;
        object d = b;

        Console.WriteLine (c==d);
        Console.WriteLine (c.Equals(d));
    }
}

这个简短示例程序的结果是

True
True
False
True

关于c# - .Equals 和 == 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/772953/

相关文章:

c# - 编译器错误消息 : CS1513: } expected

c# - 将任意 bool 条件列表合并到Nest查询中

Python从列表中删除相同的字符

c# - MVP 和丰富的用户界面

c# - "readonly"对接口(interface)中的 getter-only ref struct 属性有意义吗?

c# - 组合一个字符常量和一个字符串文字来创建另一个常量

c# - 如何使用 DateTime 类获取 StackOverflow 样式的时间戳?

c# - 移植WinForms拖拽到WPF拖拽

python - 是否有 Python 模块来解析原始字符串中的换行符符号?

ruby - 如何使用文字标量样式在 YAML 中转储字符串?