Object.ReferenceEquals(Object, Object) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Determina se as instâncias especificadas Object são a mesma instância.
public:
static bool ReferenceEquals(System::Object ^ objA, System::Object ^ objB);
public static bool ReferenceEquals(object objA, object objB);
static member ReferenceEquals : obj * obj -> bool
Public Shared Function ReferenceEquals (objA As Object, objB As Object) As Boolean
Parâmetros
- objA
- Object
O primeiro objeto a comparar.
- objB
- Object
O segundo objeto para comparar.
Devoluções
true se objA for a mesma instância que objB ou se ambos forem nulos; caso contrário, false.
Exemplos
O exemplo seguinte serve ReferenceEquals para determinar se dois objetos são a mesma instância.
object o = null;
object p = null;
object q = new Object();
Console.WriteLine(Object.ReferenceEquals(o, p));
p = q;
Console.WriteLine(Object.ReferenceEquals(p, q));
Console.WriteLine(Object.ReferenceEquals(o, p));
// This code produces the following output:
// True
// True
// False
let o: obj = null
let mutable p: obj = null
let q = obj ()
printfn $"{Object.ReferenceEquals(o, p)}"
p <- q
printfn $"{Object.ReferenceEquals(p, q)}"
printfn $"{Object.ReferenceEquals(o, p)}"
// This code produces the following output:
// True
// True
// False
Public Class App
Public Shared Sub Main()
Dim o As Object = Nothing
Dim p As Object = Nothing
Dim q As New Object
Console.WriteLine(Object.ReferenceEquals(o, p))
p = q
Console.WriteLine(Object.ReferenceEquals(p, q))
Console.WriteLine(Object.ReferenceEquals(o, p))
End Sub
End Class
' This code produces the following output:
'
' True
' True
' False
'
Observações
Ao contrário do Equals método e do operador de igualdade, o ReferenceEquals método não pode ser sobreposto. Por causa disso, se quiseres testar duas referências de objetos para igualdade e não tiveres a certeza da implementação do Equals método, podes chamar o ReferenceEquals método.
No entanto, o valor de retorno do ReferenceEquals método pode parecer anómalo nestes dois cenários:
Ao comparar tipos de valor. Se
objAeobjBforem tipos de valor, são encaixados antes de serem passados para o ReferenceEquals método. Isto significa que, se eobjAobjBrepresentam a mesma instância de um tipo de valor, o ReferenceEquals método devolve no entantofalse, como mostra o exemplo seguinte.int int1 = 3; Console.WriteLine(Object.ReferenceEquals(int1, int1)); Console.WriteLine(int1.GetType().IsValueType); // The example displays the following output: // False // Truelet int1 = 3 printfn $"{Object.ReferenceEquals(int1, int1)}" printfn $"{int1.GetType().IsValueType}" // The example displays the following output: // False // TruePublic Module Example Public Sub Main Dim int1 As Integer = 3 Console.WriteLine(Object.ReferenceEquals(int1, int1)) Console.WriteLine(int1.GetType().IsValueType) End Sub End Module ' The example displays the following output: ' False ' TruePara informações sobre os tipos de valor do boxe, veja Boxe e Unboxing.
Ao comparar cordas. Se
objAeobjBforem cadeias, o ReferenceEquals método retornatruese a cadeia estiver internada. Não realiza um teste de igualdade de valor. No exemplo seguinte,s1es2são iguais porque são duas instâncias de uma única corda internada. No entanto,s3es4não são iguais, porque embora tenham valores idênticos de cadeia, essa cadeia não está internada.String s1 = "String1"; String s2 = "String1"; Console.WriteLine("s1 = s2: {0}", Object.ReferenceEquals(s1, s2)); Console.WriteLine("{0} interned: {1}", s1, String.IsNullOrEmpty(String.IsInterned(s1)) ? "No" : "Yes"); String suffix = "A"; String s3 = "String" + suffix; String s4 = "String" + suffix; Console.WriteLine("s3 = s4: {0}", Object.ReferenceEquals(s3, s4)); Console.WriteLine("{0} interned: {1}", s3, String.IsNullOrEmpty(String.IsInterned(s3)) ? "No" : "Yes"); // The example displays the following output: // s1 = s2: True // String1 interned: Yes // s3 = s4: False // StringA interned: Noopen System let s1 = "String1" let s2 = "String1" printfn $"s1 = s2: {Object.ReferenceEquals(s1, s2)}" printfn $"""{s1} interned: {if String.IsNullOrEmpty(String.IsInterned s1) then "No" else "Yes"}""" let suffix = "A" let s3 = "String" + suffix let s4 = "String" + suffix printfn $"s3 = s4: {Object.ReferenceEquals(s3, s4)}" printfn $"""{s3} interned: {if String.IsNullOrEmpty(String.IsInterned s3) then "No" else "Yes"}""" // The example displays the following output: // s1 = s2: True // String1 interned: Yes // s3 = s4: False // StringA interned: NoModule Example Public Sub Main() Dim s1 As String = "String1" Dim s2 As String = "String1" Console.WriteLine("s1 = s2: {0}", Object.ReferenceEquals(s1, s2)) Console.WriteLine("{0} interned: {1}", s1, If(String.IsNullOrEmpty(String.IsInterned(s1)), "No", "Yes")) Dim suffix As String = "A" Dim s3 = "String" + suffix Dim s4 = "String" + suffix Console.WriteLine("s3 = s4: {0}", Object.ReferenceEquals(s3, s4)) Console.WriteLine("{0} interned: {1}", s3, If(String.IsNullOrEmpty(String.IsInterned(s3)), "No", "Yes")) End Sub End Module ' The example displays the following output: ' s1 = s2: True ' String1 interned: Yes ' s3 = s4: False ' StringA interned: NoPara mais informações sobre o estágio de cordas, veja String.IsInterned.