歡迎跟我連絡

本頁最下方有Web MSN可以直接跟我交談喔!
免安裝程式...哈哈 歡迎聊天

2008年7月19日 星期六

Class與Struct的區別 (C#)

透過下面的例子說明,
using System;
namespace StructVSClass
{
//定義類別
class myRef {public int x;}
//定義結構
struct myVal {public int x;}

class Class1
{
[STAThread]
static void Main(string[] args)
{
myRef r1=new myRef();
myVal v1=new myVal();
r1.x=10;
v1.x=10;
Console.WriteLine("Before :");
Console.WriteLine("r1.x="+r1.x);
Console.WriteLine("v1.x="+v1.x);

myRef r2=r1;
myVal v2=v1;
r1.x=20;
v2.x=30;

Console.WriteLine("After:");
Console.WriteLine("r1.x="+r1.x+";r2.x="+r2.x);
Console.WriteLine("v1.x="+v1.x+";v2.x="+v2.x);
}
}
}
輸出結果:
Before:
r1.x=10
v1.x=10
After:
r1.x=20;r2.x=20
v1.x=10;v2.x=30

所以修改r2會影響r1 (Class是Reference Type)
但是修改v2並不會影響v1 (Struct是Value Type)

1 個回應:

匿名 提到...

Difference between struct and class
1. Struct is a value type (stored in stack).
Class is a reference type(stored in heap).
2. Struct is not identifical.
Class is identification.
3. default modifier for Struct is public, so it is accessible.
default modifier for class is private, so it is inaccessible.
4. it is not recommend to modify struct default construction function.
5. Struct could not be override.

MSN狀態(我在線上時,可以跟我交談喔)