首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Object.ReferenceEquals的行为与预期不同

Object.ReferenceEquals的行为与预期不同
EN

Stack Overflow用户
提问于 2015-05-06 10:16:30
回答 2查看 130关注 0票数 1

我在c#中遇到了一个误解的行为,这里是一个完整的例子,甚至Resharper也给我展示了我的期望

代码语言:javascript
复制
using System;

namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            var str = EmptyArray<string>.Instance;
            var intTest = EmptyArray<int>.Instance;
            var intTest1 = EmptyArray<int>.Instance;  
            var str1 = EmptyArray<string>.Instance;
            int i=0;
            int j = 0;
            string s = "";             
            Console.WriteLine(str.GetType());
            Console.WriteLine(intTest.GetType());
            if (Object.ReferenceEquals(str,str1))
            {
                Console.WriteLine("References are equals");
            }
            if (Object.ReferenceEquals(intTest,intTest1)) ;            
            {
                Console.WriteLine("References are equals");
            }
            //this will be true so Why ? 
            if (Object.ReferenceEquals(intTest,str)) ;            
            {
                Console.WriteLine("References are equals");
            }
            //I know this will be always false 
            if (Object.ReferenceEquals(i,j))
            {

            }
            //this will be always false 
            if (object.ReferenceEquals(i,s))
            {

            }


        }
    }

    public static class EmptyArray<T>
    {
        public static readonly T[] Instance;

        static EmptyArray()
        {
            Instance =  new T[0];
        }
    }
}

这里的奇怪行为对我来说,这是真的,那么为什么?就连Resharper也警告我说:“表达总是错误的”。

代码语言:javascript
复制
            //
            if (Object.ReferenceEquals(intTest,str)) ;            
            {
                Console.WriteLine("References are equals");
            }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-06 10:23:21

这是因为if语句末尾有分号

代码语言:javascript
复制
if (Object.ReferenceEquals(intTest,str)) ;   // remove this semicolon.

这里是工作点网小提琴。

票数 5
EN

Stack Overflow用户

发布于 2015-05-06 10:24:08

那是因为你有一个错误:

代码语言:javascript
复制
 if (Object.ReferenceEquals(intTest,str)) ;   

检查结果为no-op,下一个块无论如何都会被执行。

如果删除分号,则不会执行该块。

代码语言:javascript
复制
if (Object.ReferenceEquals(intTest, str)) 
{
    Console.WriteLine("References are equals");
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30073850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档