C# Object.ReferenceEquals的行为不符合预期
我在c#中遇到了一个被误解的行为,这是一个完整的例子,即使Resharper也能告诉我我的期望C# Object.ReferenceEquals的行为不符合预期,c#,C#,我在c#中遇到了一个被误解的行为,这是一个完整的例子,即使Resharper也能告诉我我的期望 using System; namespace ConsoleApplication11 { class Program { static void Main(string[] args) { var str = EmptyArray<string>.Instance; var intTest
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];
}
}
}
这是因为在if语句的末尾有分号
if (Object.ReferenceEquals(intTest,str)) ; // remove this semicolon.
这是因为在if语句的末尾有分号
if (Object.ReferenceEquals(intTest,str)) ; // remove this semicolon.
正在使用的是网络提琴。这是因为您的打字错误:
if (Object.ReferenceEquals(intTest,str)) ;
检查结果为no op,下一个块仍将执行
如果删除分号,则不会执行块
if (Object.ReferenceEquals(intTest, str))
{
Console.WriteLine("References are equals");
}
那是因为你有一个打字错误:
if (Object.ReferenceEquals(intTest,str)) ;
检查结果为no op,下一个块仍将执行
如果删除分号,则不会执行块
if (Object.ReferenceEquals(intTest, str))
{
Console.WriteLine("References are equals");
}
请解释你的代码的功能和期望。Resharper不是silverbullet@CodeCaster我希望比较int和字符串之间的对象引用应该是false@Mat我完全相信agree@CodeCaster那是不同的代码。您的代码比较为空请解释您的代码的功能和期望。Resharper不是silverbullet@CodeCaster我希望比较int和字符串之间的对象引用应该是false@Mat我完全相信agree@CodeCaster那是不同的代码。您的代码比较空值