C#中的引用类型和值类型
1. 引用类型和值类型的分类
分类如下所示:
类别 | 描述 | |
值类型
|
基本数据类型
| 有符号整型:sbyte,short,int,long |
无符号长整型:byte,ushort,uint,ulong | ||
浮点型:float,double | ||
字符型:char | ||
布尔型:bool | ||
枚举类型 | 枚举型:enum | |
结构类型 | 结构:struct | |
引用类型 |
类 | 基类:System.Object |
字符串:string | ||
自定义类:class | ||
接口 | 接口:interface | |
数组 | 数组:int[], string[] | |
委托类型 | 用户自定义类型:delegate |
2. 值类型举例
2.1 基本数据类型
2.1.1 sbyte
sbyte sByte = 127;
2.1.2 short
short x = 5;
2.1.3 int
int x = 100;
2.1.4 long
long l = 123456;
2.1.5 byte
byte myByte = 255;
2.1.6 ushort
ushort myShort = 65535;
2.1.7 uint
uint myInt = 34567123;
2.1.8 ulong
ulong uLong = 3552525;
2.1.9 float
float f = 3.5F;
2.1.10 double
double d = 3D;
2.1.11 char
char x = ‘a’;
2.1.12 bool
bool b = true;
2.2 枚举类型
2.2.1 enum
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
2.3 结构类型
2.3.1 struct
public struct Book{
publicdecimal price;
publicstring title;
publicstring author;
}
3. 引用类型举例
3.1 接口
3.1.1 interface
interface InterfaceTest{
voidPlay();
}
class ImpClass : InterfaceTest{
voidInterfaceTest.Play(){
Console.WriteLine(“Iwant to play”);
}
static voidMain(){
ImpClassobj = new ImpClass();
obj.Play();
}
}
3.2 数组
3.2.1 int[]
class TestInt{
staticvoid Main(){
int[]array = {1,2,3,4,5};
for(inti in array){
Console.WriteLine(i);
}
}
}
3.3 委托
3.3.1 delegate
delegate double MatchAction(double num);
class DelegateTest{
staticdoule Double(double input){
returninput * 2;
}
staticvoid Main(){
MatchActionma = Double;
doublemultByTwo = ma(4.5);
Console.WriteLine(“multByTwo:{0}”,multByTwo);
}
}
3.4 类
3.4.1 Object
class ObjectTest{
public int i = 10;
}
class MainTest{
object a;
a = 1;
Console.WriteLine(a);
Console.WriteLine(a.GetType());
Console.WriteLine(a.ToString());
a = newObjectTest();
ObjectTestclassRef;
classRef =(ObjectTest)a;
Console.WriteLine(classRef.i);
}
3.4.2 string
string a = “hello”;
string b = “h”;
b +=”ello”;
Console.WriteLine(a == b);
Console.WriteLine((object)a == (object)b);
3.4.3 class
class Student{
privateint age;
privatestring name;
privateint stuNum;
publicStudent(int age, string name, int stuNum){
this.age= age;
this.name= name;
this.stuNum= stuName;
}
publicvoid Print(){
Console.WriteLine(“name:{0},age:{1}, stuNum:{2}”, name, age, stuNum);
}
}
class StuTest{
staticvoid Main(){
Studentstu1 = new Student(10, “WangLei”, 1);
Studentstu2 = new Student(12, “ZhangYuan”, 10);
stu1.Print();
stu2.Print();
}
}