简体   繁体   English

为什么Object.Equals的参数不是“输入”(输入)?

[英]Why parameter of Object.Equals is not 'in' (input)?

Following ( incorrect/dangerous ) code 遵循( 不正确/危险 )代码

class EvilClass
{
    protected int x;

    public EvilClass(int x)
    {
        this.x = x;
    }

    public override bool Equals(Object obj)
    {
        if ((obj == null) || !this.GetType().Equals(obj.GetType()))
        {
            return false;
        }
        else
        {
            EvilClass p = (EvilClass)obj;
            p.x = 42;
            return (x == p.x);
        }
    }

    public override int GetHashCode()
    {
        return (x << 2);
    }

    public override string ToString()
    {
        return String.Format("EvilClass({0})", x);
    }
}

void Main()
{
    var e1 = new EvilClass(1);
    var e2 = new EvilClass(2);

    var equals = e1.Equals(e2);
    Console.WriteLine("{0}", e1.ToString());
    Console.WriteLine("{0}", e2.ToString());
}

Output: 输出:

EvilClass(1)
EvilClass(42)

As you can see, call of e1.Equals(e2) modify e2 . 如您所见,调用e1.Equals(e2)修改e2 If we mark parameter as in compiler would not allow us to modify it. 如果编译器中将参数标记为,则不允许我们对其进行修改。

Object.Equals() not suppose to change it's parameter - so why parameter is not in (input) parameter? 的Object.Equals()不要以为改变它的参数-那么,为什么参数不在 (输入)参数?

The most obvious reason is that in was introduced in C# 7.2, while object.Equals has been around since the very first version of .net. 最明显的原因是in是C#7.2中引入的,而object.Equals自.net的第一个版本以来就存在。

The other reason is that it wouldn't actually change anything. 另一个原因是它实际上不会改变任何东西。 in prevents from mutating the reference, not the actual object. in从突变的引用,而不是实际的对象防止。 If you try this: 如果您尝试这样做:

public bool Equals2(in Object obj)
{
    if ((obj == null) || !this.GetType().Equals(obj.GetType()))
    {
        return false;
    }
    else
    {
        EvilClass p = (EvilClass)obj;
        p.x = 42;
        return (x == p.x);
    }
}

Then the output will still be: 然后输出仍然是:

EvilClass(1)
EvilClass(42)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM