等于vs ==表现不同

时间:2016-06-24 10:40:00

标签: c#

等于和==检查参考相等性。 但它的行为有何不同? 在这里

Console.WriteLine(c == d); //False
Console.WriteLine(c.Equals(d)); //True

Console.WriteLine(cc == dd); //True
Console.WriteLine(cc.Equals(dd));//True

有人可以解释幕后发生的事情。

    //https://blogs.msdn.microsoft.com/csharpfaq/2004/03/29/when-should-i-use-and-when-should-i-use-equals/
public void StringDoubleEqualsVsEquals()
{
    // 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); //True
    Console.WriteLine(a.Equals(b)); //True

    // 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); //False
    Console.WriteLine(c.Equals(d)); //True

    /*************************************************************************/
    Console.WriteLine(Environment.NewLine);
    string aa = "1";
    string bb = "1";

    Console.WriteLine(aa == bb);//True
    Console.WriteLine(aa.Equals(bb));//True

    object cc = aa;
    object dd = bb;

    Console.WriteLine(cc.GetType());//System.String
    Console.WriteLine(dd.GetType());//System.String

    Console.WriteLine(cc == dd);//True
    Console.WriteLine(cc.Equals(dd));//True

    Console.ReadKey();
}

1 个答案:

答案 0 :(得分:0)

运营商Object.EqualsObject.Equals本身就是可以独立实施的不同内容。通常,实现==以检查值相等,而==检查引用相等性。但是,string上的运算符var app = angular.module('MyApp', []); app.service('MyService', function () { var property = 'First'; this.myFunc = function (x) { return x*5; } }); // controller 2 under second app module var app = angular.module('AnotherApp',[]); app.controller("AnotherAppCtrl", function($scope,MyService) { $scope.value = MyService.myFunc(4); });实际上也会检查值是否相等。

相关问题