01.定义
值类型
int number1 = 42;
char letter = 'A';
float Pi = 3.14f;
int number2 = number1;
float Pi2 = Pi;
Console.WriteLine(number2); //42
Console.WriteLine(Pi2);//3.14
number1 = 50;
Pi = 3.14159f;
Console.WriteLine(number2); //42
Console.WriteLine(Pi2);//3.14
引用类型
string a = "一休";
string b = a;
Console.WriteLine(b); //一休
//string是不可变的 当创建新的string"聪明的一休"
//把变量a的引用指向新的string""聪明的一休",b还是指向原来的"一休";
a = "聪明的一休";
Console.WriteLine(b); //一休
02.结构
(1)struct要么不声明构造函数(会有一个默认的无参构造函数),要么声明有参构造函数,struct不支持显示声明无参构造函数.
(2)struct的构造函数支持重载.
(3)struct的所有构造函数内部必须对所有字段和属性赋值.
(4)使用struct的方法前,必须已经对所有字段赋过值.
using System;
namespace Objects
{
class Program
{
static void Main(string[] args)
{
Student student=new Student();
Console.WriteLine(student.attr.Name+":"+student.attr.Age); //一席 1
Console.ReadKey();
}
}
class Student
{
public struct Attr
{
public int Age;
public string Name;
//必须把结构中的变量初始化
public Attr(int age, string name)
{
this.Name = name;
this.Age = age;
}
}
//结构初始化
public Attr attr=new Attr(1,"一席");
}
}
当没有提供默认的构造函数时,C#编译器会赋给结构一个默认的值
class Program
{
static void Main(string[] args)
{
Student student=new Student();
Console.WriteLine(student.attr.Name+":"+student.attr.Age); // null 0
Console.ReadKey();
}
}
class Student
{
public struct Attr
{
public int Age;
public string Name;
}
public Attr attr;
}
1.结构体没有无参数构造方法 必须得提供一个有参数的构造函数初始化字段
2.使用new关键字创建结构对象,并且调用构造方法 但是结构也可以不使用new关键字
如果不使用new关键字 则结构体的字段都是保持未初始化 初始值为0 3.结构不能继承结构或继承类,所有结构继承System.ValueType[隐士继承]后者继承System.Object
4.可以实现接口
5.声明的时候不能初始化结构字段
6.结构是值类型 不是引用类型 例如A复制B结构 只是复制数据 没有复制引用
7如果当做参数传递最好前面加引用符号ref
03.default
04.装箱
//装箱
int a = 100;
object b = a;
string c=b.ToString();
Console.WriteLine(c.GetType());
//拆箱
object d = "565";
int e = int.Parse(d.ToString());
Console.WriteLine(e.GetType());
int a = 10;
//object是所有类型的基类
//01将值类型的i装箱
//02值的拷贝
object obj = a;
//double c = (double)obj; //这个必须先拆箱转换为int类型
double c = (double)(int)obj;