C#中如何定义结构体

发布时间:2021-07-29 15:51:01 作者:Leah
来源:亿速云 阅读:684

这篇文章将为大家详细讲解有关C#中如何定义结构体,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

C#结构体定义的情况:

C#结构体定义也可以象类一样可以单独定义.

class  a{};  struct a{};

C#结构体定义也可以在名字前面加入控制访问符.

public struct student{};  internal struct student{};

如果结构体student没有publice或者internal的声明 类program就无法使用student结构定义 obj对象

如果结构体student的元素没有public的声明,对象obj就无法调用元素x

因为默认的结构体名和元素名是private类型

C#结构体定义之程序:

using System;  public struct student  {     public int x;  };   class program  {  public static void Main()  {   student obj=new student();   obj.x=100;     }   };

在结构体中也可以定义静态成员与类中一样,使用时必须用类名,或结构名来调用不属于实例,声明时直接定义.

C#结构体定义程序:

using System;  public struct student  {   public static int a = 10;  };  class exe  {   public static void Main()  {   Console.WriteLine( student.a = 100);  }  };

using System;  class base {  public struct student  {   public static int a = 10;  };  }  class exe  {   public static void Main()  {   Console.WriteLine( base.student.a = 100);  }  };

在结构体中可以定义构造函数以初始化成员,但不可以重写默认无参构造函数和默认无参析构函数

C#结构体定义程序:

public struct student  {     public int x;     public int y;     public static int z;     public student(int a,int b,int c)  {  x=a;  y=b;   student.z=c;  }   };

在结构体中可以定义成员函数。

C#结构体定义程序:

public struct student  {     public void list()  {  Console.WriteLine("这是构造的函数");  }    };

结构体的对象使用new运算符创建(obj)也可以直接创建单个元素赋值(obj2)这是与类不同的因为类只能使用new创建对象

C#结构体定义程序:

public struct student  {     public int x;     public int y;     public static int z;     public student(int a,int b,int c)  {  x=a;  y=b;   student.z=c;  }   };  class program  {   public static void Main()  {    student obj=new student(100,200,300);    student obj2;    obj2.x=100;    obj2.y=200;    student.z=300;  }  }

在使用类对象和函数使用时,使用的是引用传递,所以字段改变

在使用结构对象和函数使用时,是用的是值传递,所以字段没有改变

C#结构体定义程序:

using System;  class class_wsy  {  public int x;  }  struct struct_wsy  {  public int x;  }  class program  {  public static void class_t(class_wsy obj)  {  obj.x = 90;  }  public static void struct_t(struct_wsy obj)  {  obj.x = 90;  }  public static void Main()  {  class_wsy obj_1 = new class_wsy();  struct_wsy obj_2 = new struct_wsy();  obj_1.x = 100;  obj_2.x = 100;  class_t(obj_1);  struct_t(obj_2);  Console.WriteLine("class_wsy obj_1.x={0}",obj_1.x);  Console.WriteLine("struct_wsy obj_2.x={0}",obj_2.x);  Console.Read();  }  }

C#结构体定义程序运行结果为:

class_wsy obj_1.x=90  struct_wsy obj_2.x=100

关于C#中如何定义结构体就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 浅谈C#结构体
  2. C# 结构体的介绍

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:flinksql 中怎么自定义udf

下一篇:java中怎么定义一个抽象属性

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》