现在的位置: 首页 > 综合 > 正文

C#内置数据类型

2013年06月26日 ⁄ 综合 ⁄ 共 1109字 ⁄ 字号 评论关闭

C# 是一种强类型语言。在变量中存储值之前,必须指定变量的类型,如以下示例所示:

 
int a = 1;
string s = "Hello";
XmlDocument tempDocument = new XmlDocument();

注意,对于简单的内置类型(如 )以及复杂的或自定义的类型(如 )都必须指定类型。

C# 包括对下面的内置数据类型的支持:

数据类型 范围

byte    

0 .. 255

sbyte

-128 .. 127

short

-32,768 .. 32,767

ushort

0 .. 65,535

int

-2,147,483,648 .. 2,147,483,647

uint

0 .. 4,294,967,295

long

-9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807

ulong

0 .. 18,446,744,073,709,551,615

float

-3.402823e38 ..3.402823e38

double

-1.79769313486232e308 ..1.79769313486232e308

decimal

-79228162514264337593543950335 .. 79228162514264337593543950335

char

一个 Unicode 字符。

string

Unicode 字符的一个字符串。

bool

True 或 False。

object

一个对象。

这些数据类型名称为 命名空间中的预定义类型的别名。 节中列出了这些类型。所有这些类型(除对象和字符串以外)均为值类型。

使用内置数据类型

内置数据类型在 C# 程序中有几种用法。

作为变量:

C#  CopyCode image复制代码
int answer = 42;
string greeting = "Hello, World!";

作为常数:

C#  CopyCode image复制代码
const int speedLimit = 55;
const double pi = 3.14159265358979323846264338327950;

作为返回值和参数:

C#  CopyCode image复制代码
long CalculateSum(int a, int b)
{
    long result = a + b;
    return result;
}

若要定义自己的数据类型,请使用类(Visual C# 速成版)枚举(Visual C# 速成版)结构(Visual C# 速成版)

转换数据类型

数据类型间的转换可以隐式完成(转换由编译器自动完成)或使用强制转换显式完成(程序员强制进行转换,并承担丢失信息的风险)。

例如:

C#  CopyCode image复制代码
int i = 0;
double d = 0;

i = 10;
d = i;        // An implicit conversion

d = 3.5;
i = (int) d;  // An explicit conversion, or "cast"

抱歉!评论已关闭.