您的位置:首页 > 编程语言 > C#

C#基础-数据类型

2016-12-04 15:47 211 查看
内存空间有 “栈” 和 “堆”

值类型存储在栈中,存储的值就是变量本身包含的值,所以存取速度比较

引用类型栈中存储的只是一个引用地址,其对象的真实数据则存储在托管的堆上。访问效率较

栈中存放对象引用,堆中存放对象数据。



值类型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 值类型
{
class Program
{
static void Main(string[] args)
{
int x = 10;
int y = x;

Console.WriteLine("x = {0}, y = {1}", x, y);

x = 100;
Console.WriteLine("x = {0}, y = {1}", x, y);

Console.ReadLine();

}
}
}

x = 10, y = 10

x = 100, y = 10

引用类型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 引用类型
{
class MyClass
{
public int a = 100;
}

class Program
{
static void Main(string[] args)
{
MyClass my1 = new MyClass();
Console.WriteLine("my1.a = {0}", my1.a);

MyClass my2 = my1;
my2.a = 500;

Console.WriteLine("my1.a = {0}, my2.a = {1}", my1.a ,my2.a);

Console.ReadLine();
}
}
}
my1.a = 100

my1.a = 500, my2.a = 500

C# 有15个 预定义类型:

-- 13个 是值类型

-- 2个 是引用类型 (string 和 object)

自定义类型:

-- 值类型:struct (结构)、enum (枚举)

--引用类型: Class (类)

先说 13个 值类型:

8个整型:



3个高精度类型: float  double decimal



2个:布尔 bool    字符 char



预定义引用类型:object  string



object  类型就是最终的父类型:

-- 可以使用 object 引用绑定任何子类型的对象

-- object 类型执行许多一般用途的基本方法,包括 Equals()、GetHashCode()、GetType() 和 Tostring()。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace @object
{
class Program
{
static void Main(string[] args)
{
object i = "C#";
object i1 = 123;
object i2 = 3.14M;

Console.WriteLine("上面三个值分别是:{0},{1},{2}",i,i1,i2);
Console.ReadLine();
}
}
}
上面三个值分别是:C#,123,3.14

string 类型:

它表示 零 或 多 Unicode 字符组成的序列。 string 是.NET Framework 中
String 的别名。

String 类型的修改更像是值类型,但它确实是
引用类型


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace @string
{
class Program
{
static void Main(string[] args)
{
string str1 = "Hello ";
string str2 = "C# !";

string str3 = str1 + str2;

Console.WriteLine(str3);

string str4 = str3;

str4 = "HI";
Console.WriteLine(str3);
Console.WriteLine(str4);

Console.ReadLine();
}
}
}




string str4 = str3;


可以看出  str3 是拷贝了一份  给 str4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# .net