我在c#中遇到了一个误解的行为,这里是一个完整的例子,甚至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];
}
}
}这里的奇怪行为对我来说,这是真的,那么为什么?就连Resharper也警告我说:“表达总是错误的”。
//
if (Object.ReferenceEquals(intTest,str)) ;
{
Console.WriteLine("References are equals");
}发布于 2015-05-06 10:23:21
发布于 2015-05-06 10:24:08
那是因为你有一个错误:
if (Object.ReferenceEquals(intTest,str)) ; 检查结果为no-op,下一个块无论如何都会被执行。
如果删除分号,则不会执行该块。
if (Object.ReferenceEquals(intTest, str))
{
Console.WriteLine("References are equals");
}https://stackoverflow.com/questions/30073850
复制相似问题