// Simple Sample public struct student0 { public int age; public string name; public student(int age, string name) { this.age = age; this.name = name; } }public class student1 { public int age; public string name; public student(int age, string name) { this.age = age; this.name = name; } }class sample { public ChangeName(student0 student) { student.name = "Inside" + student.name; } public ChangeName(student1 student) { student.name = "Inside" + student.name; } static void Main() { student0 chung(25, "CSharp"); student1 dong(25, "dotNET"); //struct is value type, 意味着在ChuangName中修改后,chung变量并没有被修改,//ChuangName改的只是chung的一个拷贝,计算机课程应该都学过呀。 ChangeName(chung); Console.WriteLine(chung.name); // 输出"Charp" //class is reference type, 意味着在ChuangName中修改后, // dong变量会被修改, //ChuangName直接改的是dong。 ChangeName(dong); Console.WriteLine(dong.name); // 输出"InsidedotNet" } }
在.net中,值类型是分配在堆栈中的,速度较快,引用类型分配到系统内存中,由garbage collection负责它的释放,因为.net中所有的类型都是从object class 派生的,而值类型要从class ValueType派生,ValueType从object class派生,引用类型直接或间接从object派生,值类型可以放到系统内容中,for example: int
在.net中,值类型是分配在堆栈中的,速度较快,引用类型分配到系统内存中,由garbage collection负责它的释放,因为.net中所有的类型都是从object class 派生的,而值类型必须从class ValueType派生,ValueType从object class派生,引用类型直接或间接从object派生就可以,值类型可以放到系统内存中,for example: int i = 0; object ob = (object)i; (Box process) int j = (int)ob (UnBox process)在box process中,值类型i赋给一个object 类型的ob后,i的具体内容就放到了系统内存中,通过ob这个变量,可以重新得回i的值,这个过程叫做unbox process.
我想知道 所谓的 struct 和 class 所谓的值类型和引用类型的区别!!
我只是想知道.哎~我举个例子:
sruct student0
{
int age;
string name;
}class student1
{
int age;
string name;
}student0 chung;
studeng1 dong;好了,我想知道他们的区别,我想知道 所谓的 struct 和 class 所谓的值类型和引用类型的区别!!
1 struct占用系统内存较少。
2 struct不支持继承,但struct可以从接口(interface)继承
3 数值类型变量值是在内存中存放的数据,引用类型变量则为数据存放的地址
public struct student0
{ public int age;
public string name;
public student(int age, string name) {
this.age = age;
this.name = name;
}
}public class student1
{
public int age;
public string name;
public student(int age, string name) {
this.age = age;
this.name = name;
}
}class sample { public ChangeName(student0 student) {
student.name = "Inside" + student.name;
} public ChangeName(student1 student) {
student.name = "Inside" + student.name;
} static void Main() {
student0 chung(25, "CSharp");
student1 dong(25, "dotNET");
//struct is value type, 意味着在ChuangName中修改后,chung变量并没有被修改,//ChuangName改的只是chung的一个拷贝,计算机课程应该都学过呀。
ChangeName(chung); Console.WriteLine(chung.name); // 输出"Charp" //class is reference type, 意味着在ChuangName中修改后,
// dong变量会被修改,
//ChuangName直接改的是dong。
ChangeName(dong);
Console.WriteLine(dong.name); // 输出"InsidedotNet"
}
}
int
int i = 0;
object ob = (object)i; (Box process)
int j = (int)ob (UnBox process)在box process中,值类型i赋给一个object 类型的ob后,i的具体内容就放到了系统内存中,通过ob这个变量,可以重新得回i的值,这个过程叫做unbox process.
Object
|__ValueType
|__studnet0class studnet1的派生关系是
Object
|__studnet1
(也许我们想要两个内容一样的不同两对象更麻烦了,也不知为什么要这么做)