结构
来源:互联网 发布:换手率炒股软件ipad版 编辑:程序博客网 时间:2024/04/30 02:15
运行结果如下:
结构可以实现接口,并且可以具有与类相同的成员。
对于类,两个变量引用统一对象是可能的,因此对一个变量进行的操作可能影响另一个变量所引用的对象。对于结构,每个变量都有自己的数据副本,因此对一个变量进行的操作不可能影响另一个变量。
一个应用程序可以只包含结构,Main()方法包含在结构中。
结构与类的区别
1. 结构是针对值的,类是针对对象的
2. 结构不支持继承,只适用于不需要扩展的对象
对于大小小于26字节的类,定义为结构更合理。
对于类,两个变量引用统一对象是可能的,因此对一个变量进行的操作可能影响另一个变量所引用的对象。对于结构,每个变量都有自己的数据副本,因此对一个变量进行的操作不可能影响另一个变量。
结构中的字段在定义时不能被初始化。结构可以包含构造函数、常数、字段、方法、性质、操作符等。在结构中不能显式声明结构的默认(没有参数的构造函数),结构本身已经提供了一个默认的构造函数以便初始化结构的成员。结构可以使用new创建结构实例,也可以不使用new实例化结构。
using System;
using System.Collections.Generic;
using System.Text;
namespace stucture
{
public struct Rectangle
{
public float x;
public float y;
public Rectangle(float a, float b)
{
x = a;
y = b;
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r1 = new Rectangle();//使用默认的构造函数
Rectangle r2 = new Rectangle(5.5f,6.5f);
Rectangle r3;
r3.x = 5;
r3.y = 6;
Console.WriteLine("the size of rectangle r1 is {0}",r1.x*r1.y);
Console.WriteLine("the size of rectangle r2 is {0}", r2.x * r2.y);
Console.WriteLine("the size of rectangle r3 is {0}", r3.x * r3.y);
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace stucture
{
public struct Rectangle
{
public float x;
public float y;
public Rectangle(float a, float b)
{
x = a;
y = b;
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r1 = new Rectangle();//使用默认的构造函数
Rectangle r2 = new Rectangle(5.5f,6.5f);
Rectangle r3;
r3.x = 5;
r3.y = 6;
Console.WriteLine("the size of rectangle r1 is {0}",r1.x*r1.y);
Console.WriteLine("the size of rectangle r2 is {0}", r2.x * r2.y);
Console.WriteLine("the size of rectangle r3 is {0}", r3.x * r3.y);
Console.ReadLine();
}
}
}