码迷,mamicode.com
首页 > Windows程序 > 详细

C#_基础_结构Struct(八)

时间:2018-06-10 19:31:54      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:默认   his   run   nbsp   string   char   OLE   pre   code   

一般情况下,不建议使用结构。

结构中可以包含多种不同类型的字段,方法

定义一个结构:

1  public struct Person
2         {
3             public string _name;//命名规范字段前前加下划线
4            public   int _age;
5            public   char _gender;
6            public QQState _state; //枚举类型
7         }

结构声明:调用

1  //声明结构变量,实质上和枚举一样,int 都是变量,
2              Person zhangsan;
3              zhangsan._name = "zhangsan";
4              zhangsan._age = 14;
5              zhangsan._state = QQState.Busy;
6              zhangsan._gender = ;

结构中也可以有方法:

 1  public struct Person
 2         {
 3             public string _name;//命名规范字段前前加下划线
 4            public   int _age;
 5            public   char _gender;
 6            public QQState _state; //枚举类型
 7             public void Run()
 8            {
 9                Console.WriteLine("Run");
10            }

调用:

zhangsan.Run();

 

结构特点:

结构和类不一样,不可以new对象。直接声明对象就可以

结构是值类型,所以对象只在栈中,不会在堆中开空间

结构没有默认的构造函数。

 

给结构加构造方法:必须把结构中所有的字段都赋值才可以

 1  /// <summary>
 2         /// 没有字段的情况
 3         /// </summary>
 4         public struct Student
 5         {
 6             public Student()
 7             {
 8 
 9             }
10             public void Study()
11             {
12 
13             }
14         }

结构new对象:

  Student s = new Student();

 

 1  /// <summary>
 2         /// 有字段的结构
 3         /// </summary>
 4         public struct Person
 5         {
 6             public string _name;//命名规范字段前前加下划线
 7             public int _age;
 8             public char _gender;
 9             public QQState _state; //枚举类型
10           
11             public Person(string name)
12             {
13                 this._name = name;
14                 this._age = 12;
15                 this._gender = ;
16                 this._state = QQState.Busy;
17 
18             }
19 
20             
21         }

 

C#_基础_结构Struct(八)

标签:默认   his   run   nbsp   string   char   OLE   pre   code   

原文地址:https://www.cnblogs.com/CeasarH/p/9163994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!