C#Struct

C#Struct 首页 / C#入门教程 / C#Struct

在C#中,类和结构是用来创建类实例的蓝图。结构用于轻量级对象,如颜色、矩形、点等。

与类不同,C#中的结构是值类型,而不是引用类型。如果您有在创建Struct之后不打算修改的数据,则它很有用。

C#结构示例

让无涯教程看一个简单的struct Rectangle示例,它有两个数据成员Width和Height。

using System;
public struct Rectangle
{
    public int width, height;

 }
public class TestStructs
{
    public static void Main()
    {
        Rectangle r = new Rectangle();
        r.width = 4;
        r.height = 5;
        Console.WriteLine("Area of Rectangle is: " + (r.width * r.height));
    }
}

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-structs.html

来源:LearnFk无涯教程网

Area of Rectangle is: 20

C#结构示例: 使用构造函数和方法

让无涯教程看看另一个结构示例,其中无涯教程使用构造函数来初始化数据,并使用方法来计算矩形的面积。

无涯教程网

using System;
public struct Rectangle
{
    public int width, height;

    public Rectangle(int w, int h)
    {
        width = w;
        height = h;
    }
    public void areaOfRectangle() { 
     Console.WriteLine("Area of Rectangle is: "+(width*height)); }
    }
public class TestStructs
{
    public static void Main()
    {
        Rectangle r = new Rectangle(5, 6);
        r.areaOfRectangle();
    }
}

输出:

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-structs.html

来源:LearnFk无涯教程网

Area of Rectangle is: 30

Note: Struct doesn't support inheritance. But it can implement interfaces.

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

后端工程师的高阶面经 -〔邓明〕

Serverless进阶实战课 -〔静远〕

操作系统实战45讲 -〔彭东〕

etcd实战课 -〔唐聪〕

Django快速开发实战 -〔吕召刚〕

图解 Google V8 -〔李兵〕

性能测试实战30讲 -〔高楼〕

深入浅出计算机组成原理 -〔徐文浩〕

如何做好一场技术演讲 -〔极客时间〕

好记忆不如烂笔头。留下您的足迹吧 :)