Home  >  Article  >  Backend Development  >  Structures and enumerations in c#

Structures and enumerations in c#

黄舟
黄舟Original
2016-12-27 14:06:36990browse

Structure

The difference from C++ is that the structure should be defined in the namespace or class. The member variables are called fields, and the fields have access control characters. An underscore must be added before each field

Example

<code class="language-c# hljs cs">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace 结构
{
    public enum Gender
    {
        男,女
    }
    //其实int也是一个结构;结构可以用来一次性声明多个不同类型的变量;
    public struct Person 
    {
        public string _name;//字段跟变量都可以存数据,只有字段有访问权限;每个字段前要加一个下划线;
        public int _age;
        public Gender _gender;
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Person zsPerson;
            zsPerson._name = "张三";
            zsPerson._age = 18;
            zsPerson._gender = Gender.男;
 
        }
    }
}

Enumeration

You cannot define an enumeration in the main function. You can declare it in the namespace, or you can declare it in this class, but you cannot declare it in a method; the essence of enumeration The above is a variable type. The enumeration name must comply with the Pascal specification. The first letter of each word must be capitalized.

For example

<code class="language-c# hljs cs">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace 枚举
{
    public enum Season
    {
        春,夏,秋,冬
    }
    class Program
    {
        //不能再main函数里定义枚举
        //在命名空间里声明可以,也可以在这个类里面声明,不能再方法里面声明;
        //枚举本质上是一个变量类型,
        //下面声明了一个枚举类型Gender;自己定义一个新的类型,需要给出其取值范围;
        public enum Gender
        {
            男,女
        }
        static void Main(string[] args)
        {
           //下面使用枚举;变量名=枚举规定的取值范围内的一个值;
            Gender gd = Gender.男;
            Console.WriteLine(gd.ToString());
            Console.ReadKey();
 
        }
    }
}</code>

The above is the structure and enumeration content in C# , for more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:c# FileStream file streamNext article:c# FileStream file stream