您的位置:首页 > 编程语言 > C#

C# 类与结构的区别

2014-03-20 22:26 363 查看
类与结构的区别

C++中结构与类的唯一区别是在于默认的访问级别,但是C#中的区别就稍微多了点,C#中如下

(1)类是引用类型,结构是值类型。

类中:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}

class Program
{
static void Main()
{
Person person1 = new Person("Leopold", 6);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);

// Declare  new person, assign person1 to it.
Person person2 = person1;

//Change the name of person2, and person1 also changes.
person2.Name = "Molly";
person2.Age = 16;

Console.WriteLine("person2 Name = {0} Age = {1}", person2.Name, person2.Age);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);

// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();

}
}


    Output:

    person1 Name = Leopold Age = 6

    person2 Name = Molly Age = 16

    person1 Name = Molly Age = 16

结构中:

public struct Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}

public class Application
{
static void Main()
{
// Create  struct instance and initialize by using "new".
// Memory is allocated on thread stack.
Person p1 = new Person("Alex", 9);
Console.WriteLine("p1 Name = {0} Age = {1}", p1.Name, p1.Age);

// Create  new struct object. Note that  struct can be initialized
// without using "new".
Person p2 = p1;

// Assign values to p2 members.
p2.Name = "Spencer";
p2.Age = 7;
Console.WriteLine("p2 Name = {0} Age = {1}", p2.Name, p2.Age);

// p1 values remain unchanged because p2 is  copy.
Console.WriteLine("p1 Name = {0} Age = {1}", p1.Name, p1.Age);

// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
  Output:

    p1 Name = Alex Age = 9

    p2 Name = Spencer Age = 7

    p1 Name = Alex Age = 9

(2)结构中可以包含构造函数,但是构造函数必须对全部字段赋值,因此结构没有默认构造函数

(3)结构不能被继承,但是结构可以实现接口

(4)结构直接继承自 System.ValueType,类继承自 System.Object

(5)结构中除非是const或者static变量,或者不能直接对变量初始化
namespace ConsoleApplication5
{
struct struct1
{
//int x = 10;		//error
int x;
string str;

//struct1(){}		//error

//struct1(int _x)	//error
//{ x = _x; }

struct1(int _x, string _str)
{
x = _x;
str = _str;
}

const int y = 10;	//OK
static int z = 100;	//OK
}
}


(6)结构可以是Nullable类型

所谓的Nullable类型就是System.Nullable<T>的实例,它的取值范围是值类型T可以表达的所有有效值 外加一个null值。

Nullable存在的意义:值类型必须初始化后才能使用,为了让值类型不用初始化,就诞生了这个类型了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息