Tipos de Dados (C# vs. Java)
This Topic discusses some of the primário similarities and differences in How dados is represented, allocated, and Garbage-Collected in Java and in C#.
Compound Tipos de Dadosdos
The concepção of a classe as a tipo de dados compound with Campos, Métodos, and Eventos is similar in Java and C#.(Herança Classe is discussed separately in the topic entitled Herança e classes derivado (C# VS Java).) C# introduces the concepção of a struct as a tipo de dados compound stack-allocated that not herança suporte.In Most Outro respects, Estruturas are Very similar to classes.Estruturas Provide a way Lightweight of relacionado together agrupamento Campos and Métodos for Use in loops Justo and Outro Scenarios onde is desempenho crítico.
Enables C# you to Criar a método destrutor that is chamado before instances of a classe are Garbage-Collected.In Java, a método finalize Can Be Used to Contain Código that cleans up Recursos before the objeto is Garbage-Collected.In C#, this função Is performed by the destrutor classe.The destrutor resembles a construtor com No Arguments and a acima caractere tilde (~).
Built-In Tipos de Dados
C# Provides Tudo the Tipos de Dados that are disponível in Java, and suporte for sem assinatura adds numerals and a Novo 128-bit Alto-Precisão ponto flutuante tipo.
For Each tipo de dados primitive in Java, biblioteca de classes the núcleo Provides a classe wrapper that it represents as a objeto Java.For exemplo, the classe Int32 wraps the tipo de dados int , and the classe Double wraps the duplo tipo de dados.
On the Outro hand, Tudo primitive Tipos de Dados in C# are Objetos in the namespace System.For Each tipo de dados, a Abreviado Nome, or alias, is provided.For , int is the short Name for System.Int32 and double is the Formulário abreviada of System.Double.
A lista de C# Tipos de Dados e seus aliases é fornecido na seguinte tabela.As you can see, the Primeiro Oito of these corresponder to the primitive Tipos disponível in Java.Anotação, however, that is 's Java boolean chamado bool in C#.
Nome Abreviado |
Classe .NET |
Type (Tipo) |
Width |
Range (BITS) |
---|---|---|---|---|
byte |
Inteiro Não Assinado |
8 |
0 to 255 |
|
sbyte |
Signed inteiro |
8 |
-128 to 127 |
|
int |
Signed inteiro |
32 |
-2.147.483.648 to 2.147.483.647 |
|
uint |
Inteiro Não Assinado |
32 |
0 to 4294967295 |
|
short |
Signed inteiro |
16 |
-32.768 to 32.767 |
|
ushort |
Inteiro Não Assinado |
16 |
0 to 65535 |
|
long |
Signed inteiro |
64 |
-922337203685477508 to 922337203685477507 |
|
ulong |
Inteiro Não Assinado |
64 |
0 to 18446744073709551615 |
|
float |
Tipo ponto flutuante Simples-Precisão |
32 |
-3.402823E38 para 3.402823E38 |
|
double |
Tipo ponto flutuante Duplo-Precisão |
64 |
-1.79769313486232e308 para 1.79769313486232e308 |
|
char |
A Simples caractere Unicode |
16 |
Símbolos Unicode Used in Texto |
|
bool |
Booleano Logical tipo |
8 |
Verdadeiro or false |
|
object |
Tipo base of all other Types |
|||
string |
Uma seqüência de caracteres |
|||
decimal |
Preciso fracionário ou tipo integral que possa representar decimal números com 29 de dígitos significativos |
128 |
10e-28 × ±1.0 para 10e28 × ±7.9 |
Because C# represents all primitive Tipos de Dados as Objetos, it is possible to chamar an método objeto on a tipo de dados primitive.Por exemplo:
static void Main()
{
int i = 10;
object o = i;
System.Console.WriteLine(o.ToString());
}
Isso é feito com a ajuda do automático conversão boxing e conversão unboxing.Para obter mais informações, consulte Boxing and Unboxing (C# Programming Guide).
Constantes
Ambos Java and C# Provide the ability to declare a variável whose valor is specified em tempo de Compilar and cannot be Alterado at tempo de execução.Java uses the modificador campo final to declare such a variável, while the uses C# const palavra-chave.In addition to const, C# Provides the palavra-chave somente leitura to declare Variáveis that can be Assigned a valor once at tempo de execução--Either in the instrução instrução or else in the construtor.After inicialização, the valor of a variável readonly Cannot Alterar.Cenário one in which readonly Variáveis are useful is When Módulos that have been compilado separately need to compartilhar dados such as a número versão.If módulo A is Updated and recompiled with a Novo número versão, módulo B can be initialized with that constante Novo valor without having to be recompiled.
Enumerações
Enumerations, or enums, are used to Agrupar nomeado Constants similar to How they are used in C and C++; They are not disponível in Java.The seguinte exemplo Defines a enumeração Simples Color.
public enum Color
{
Green, //defaults to 0
Orange, //defaults to 1
Red, //defaults to 2
Blue //defaults to 3
}
Integral values also can be Assigned to Enumerations as shown in the seguinte declaração enum:
public enum Color2
{
Green = 10,
Orange = 20,
Red = 30,
Blue = 40
}
O seguinte exemplo de código chama o método GetNames do tipo Enum para exibir o disponível constantes para uma enumeração.Em seguida, ele atribui um valor para uma enumeração e exibe o valor.
class TestEnums
{
static void Main()
{
System.Console.WriteLine("Possible color choices: ");
//Enum.GetNames returns a string array of named constants for the enum.
foreach(string s in System.Enum.GetNames(typeof(Color)))
{
System.Console.WriteLine(s);
}
Color favorite = Color.Blue;
System.Console.WriteLine("Favorite Color is {0}", favorite);
System.Console.WriteLine("Favorite Color value is {0}", (int) favorite);
}
}
Saída
Possible color choices:
Green
Orange
Red
Blue
Favorite Color is Blue
Favorite Color value is 3
Seqüências
Tipos de Cadeia de Caracteres em Ambos Java e C# apresentam um comportamento parecido com pequenas diferenças.Both Types seqüência de caracteres are imutável, meaning that the values of the Cadeia de caracteres cannot be changed once the Cadeia de caracteres have been Criado.In Ambos instances, Métodos that Aparecer to modify the real de conteúdo of a Cadeia de Caracteres actually Criar a Novo Cadeia de Caracteres to Return, leaving the original inalterado Cadeia de Caracteres.O processo de comparar valores Cadeia de Caracteres é diferente no C# e Java.Para comparar valores Cadeia de Caracteres de Java, os desenvolvedores precisam chamar o método em um tipo Cadeia de Caracteres como compara a operador equals== referência tipos Por padrão.In C#, Developers can use the == or operadores != to compare values Cadeia de Caracteres directly.Even though a Cadeia de Caracteres is a tipo de referência in the == , C# and will operador !=, Por padrão, compare the values Cadeia de Caracteres rather then Referências.
Just LIKE in Java, C# Developers should not use the tipo seqüência de caracteres for concatenating Cadeia de caracteres to avoid the sobrecarga of Creating Novo seqüência de caracteres classes every tempo is the seqüência de caracteres concatenated.INSTEAD, Developers can use the classe StringBuilder , which is functionally equivalente to the classe StringBuffer Java.
Literals Cadeia de Caracteres
C# fornece a capacidade para evitar o uso de seqüências de escape como "\t" de guia ou "\" para caracteres barra invertida em constantes Cadeia de Caracteres.A Fazer This, declare Simply the Cadeia de Caracteres verbatim Using the @ Símbolo to precede the atribuída of the valor da Cadeia de Caracteres.The seguinte apresentação Examples How to Use Characters escape and how to literals Cadeia de Caracteres atribuir:
static void Main()
{
//Using escaped characters:
string path1 = "\\\\FileShare\\Directory\\file.txt";
System.Console.WriteLine(path1);
//Using String Literals:
string path2 = @"\\FileShare\Directory\file.txt";
System.Console.WriteLine(path2);
}
Converting and Casting
Ambos Java and C# Follow similar Regras for the Automático conversão and conversão of Tipos de Dados.
LIKE Java, C# supports Ambos conversions tipo IMPLICIT and EXPLICIT.In the maiúscminúsc of widening conversions, the conversions are IMPLICIT.For example, the following conversion from int to long is implicit, as in Java:
int int1 = 5;
long long1 = int1; //implicit conversion
The seguinte is a lista of conversions IMPLICIT between .NET Framework Tipos de Dados:
Tipo de origem |
Tipo de destino |
---|---|
Byte |
short, ushort, int, uint, long, ulong, Flutuar, duplo, or decimal |
Sbyte |
Abreviado, int, long, Flutuar, duplo, or decimal |
int |
Long, Flutuar, duplo, or decimal |
Uint |
Long, ulong, Flutuar, duplo, or decimal |
Short |
int, long, Flutuar, duplo, or decimal |
Ushort |
int, uint, comprimento, ulong, Flutuar, duplo, ou decimal |
Long |
Flutuar, duplo, or decimal |
Ulong |
Flutuar, duplo, or decimal |
Float |
double |
Char |
ushort, int, uint, long, ulong, Flutuar, duplo, or decimal |
You Expressions CAST that you desejar to converter explicitamente Using the same sintaxe as Java:
long long2 = 5483;
int int2 = (int)long2; //explicit conversion
The seguinte tabela Listas EXPLICIT conversions.
Tipo de origem |
Tipo de destino |
---|---|
Byte |
sbyte or Car |
Sbyte |
byte, ushort, uint, ulong, or Car |
int |
sbyte, byte, short, ushort, uint, ulong, or Car |
Uint |
sbyte, byte, short, ushort, int, or Car |
Short |
sbyte, byte, ushort, uint, ulong, or Car |
Ushort |
byte, sbyte, Abreviado, or Car |
Long |
sbyte, byte, short, ushort, int, uint, ulong, or Car |
Ulong |
sbyte, byte, short, ushort, int, uint, long, or Car |
Float |
byte, sbyte, short, ushort, int, uint, long, ulong, Car, ordecimal |
Double |
byte, sbyte, short, ushort, int, uint, long, ulong, Car, Flutuar, or decimal |
Char |
byte, sbyte, or Abreviado |
Decimal |
byte, sbyte, curtos, ushort, int, uint, longo, ulong, Car, Flutuar ou duplo |
Valor e tipos de referência
C# oferece suporte a dois tipos de variável tipos:
Tipos de valor
These are the interno primitive Tipos de Dados, such as Car, int, and Flutuar, as well as User-defined Tipos Declared com struct.
Tipos de referência
deCdeldeadesdesdeedesde deadendedde deodetdehdeederde deTdeydepdeedesde deddeadeddeodesde decdeodemdepdeldeedexdeodesde detdehdeadetde deaderdeede decdeodendesdetderdeudecdetdeededde defderdeodemde detdehdeede detdeydepdeedesde depderdeidemdeidetdeidevdeede.deVariáveis of such Tipos Do Not Contain an instância of the tipo, but merely a Referência to an instância.
If you Criar valor Two-tipo Variáveis, j, as follows, then i and j are completely Independent of each Outro and i:
int i = 10;
int j = 20;
They are given separar Locations memória:
If you Alterar the valor of one of these Variáveis, the Outro will naturally not be affected.For instância, If You have an expressão such as the seguinte, then there não is still conexão between the Variáveis:
int k = i;
That is, If You Alterar the valor of i, k will remain at the valor that i had at the tempo of the atribuída.
i = 30;
System.Console.WriteLine(i.ToString()); // 30
System.Console.WriteLine(k.ToString()); // 10
Referência Tipos, however, trabalhar differently.For instância, you Could declare Two Variáveis as follows:
Employee ee1 = new Employee();
Employee ee2 = ee1;
Agora, como as classes são tipos de referência em C#, ee1 é conhecido como uma referência para Employee.The Primeiro of the previous Lines Two CREATES an instância of Employee in memória, and Sets ee1 to Reference IT.Assim, quando você define ee2 a ee1 igual, ele contém um Duplicar da referência para a classe na memória.Se você propriedades alteração agora em ee2, as propriedades em ee1 refletir essas alterações, pois Ambos apontar para o mesmo objeto na memória, como mostra o seguinte:
Boxing e Unboxing
O processo de converter um tipo de valor para um tipo de referência é chamado conversão boxing.É o processo inverso, converter um tipo de referência um tipo valor, chamado conversão unboxing.Isso é ilustrado no seguinte Código:
int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing
Java requer que você executar tais conversões manualmente.Primitive Tipos de Dados can be Convertido em Objetos of classes wrapper by constructing such Objetos, or conversão boxing.deSdeidemdeideldeaderdeldeyde,de detdehdeede devdeadeldeudeedesde deodefde detdeydepdeedesde de depderdeidemdeidetdeidevdeede decdeadende debdeede deedexdetderdeadecdetdeededde defderdeodemde detdehdeede deOdebdejdeedecdetdesde deodefde dewderdeadepdepdeederde deCdeldeadesdesdeedesde debdeyde de deadende de de deodende desdeudecdehde deOdebdejdeedecdetdesde,de deoderde de.deFor Mais Informações Sobre conversão boxing and conversão unboxing, see Conversion boxing (C# Programming Guide) or Unboxing Conversion (Guide Programming C#).
Consulte também
Conceitos
Referência
Tipos de dados (guia de programação C#)