C#结构体和类的区别 代码实例解释
区别1:结构体是值类型,值类型在堆栈上分配地址,所有的基类型都是结构类型,例如
:int 对应System.int32结构,string对应system.string 结构 ,通过使用结构可以创
建更多的值类型
类是引用类型:引用类型在堆上分配地址
本质上可以看出来一个问题就是值类型是可以赋值创新的结构体的,而类也就是引用类
型值能复制引用类型
区别2. :结构体不能被继承。结构是隐式的sealed,可以继承其他类和接口
类除非显示的申明sealed 否则可以继承其他类和接口,自身也可以继承
实例如下:
/*
* Title:About Class diff struct
*Author:stephenzhou
*datetime :2012-06-29
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace classandstruct
{
class Program
{
static void Main(string[] args)
{
StructExpone sexp1 = new StructExpone();
Console.WriteLine("在结构中实例化exp1后,没有实例化成员" );
Console.WriteLine("Frist is :{0},Second is {1},Third is {2}", sexp1.Frist, sexp1.Second, sexp1.Third);
StructExpone sexp2 = new StructExpone(1, 2, 3);
Console.WriteLine("在结构中实例化exp2后,在构造函数中传值赋值到结构体成员");
Console.WriteLine("Frist is :{0},Second is {1},Third is {2}", sexp2.Frist, sexp2.Second, sexp2.Third);
ClassEptwo cexp1 = new ClassEptwo(1,2,3);
Console.WriteLine("在结构中实例化exp1后,没有实例化成员");
Console.WriteLine("Frist is :{0},Second is {1},Third is {2}", cexp1.Frist, cexp1.Second, cexp1.Third);
Console.ReadLine();
}
}
struct StructExpone
{
public StructExpone(int str1, int str2, int str3)
{
Frist=str1;
Second = str2;
Third = str3;
}
public int Frist, Second, Third;
}
public class ClassEptwo
{
public ClassEptwo(int str1, int str2, int str3)
{
Frist = str1;
Second = str2;
Third = str3;
}
public int Frist, Second, Third;
}
}