首页 > 解决方案 > 为什么 int 和 string 情况下的结果不同?

问题描述

我正在学习 c#,但我无法理解为什么以下代码中的结果不同:

public class Thing
{
    public object Data = default(object);
    public string Process(object input)
    {
        if (Data == input)
        {
            return "Data and input are the same.";
        }
        else
        {
            return "Data and input are NOT the same.";
        }
    }
}

和里面的主要方法:

var t1 = new Thing();
t1.Data = 42;
Console.WriteLine($"Thing with an integer: {t1.Process(42)}");
var t2 = new Thing();
t2.Data = "apple";
Console.WriteLine($"Thing with a string: {t2.Process("apple")}");

输出是:

Thing with an integer: Data and input are NOT the same.
Thing with a string: Data and input are the same.

标签: c#

解决方案


这种行为的根源是拳击。这是在将 .net 值类型(如整数)分配给对象引用时需要创建一个对象来保存该值。因为您这样做了两次——首先是在分配42给时Data,然后42作为对象参数传递,所以它们被装箱到遵守引用相等的不同对象中。

字符串已经是对象,但它们是 .net 中的一种特殊类型,它覆盖了相等性 - 请参阅规则


推荐阅读