我在c#中遇到了一个被误解的行为.这里是完整的例子Even Resharper告诉我我的期望
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];
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个奇怪的行为对我来说这将是真的,为什么呢?即使是Resharper也会给我一个警告,说"表达总是假的".
//
if (Object.ReferenceEquals(intTest,str)) ;
{
Console.WriteLine("References are equals");
}
Run Code Online (Sandbox Code Playgroud)
那是因为你在if语句结束时有分号
if (Object.ReferenceEquals(intTest,str)) ; // remove this semicolon.
Run Code Online (Sandbox Code Playgroud)
这是工作点网小提琴.