Speaking of classes in C #

Source: Internet
Author: User
Tags modifiers

1. What is a class?

Object-oriented language, the most basic is the class. In C #, classes are defined like this: A class represents a set of objects that have public properties and behaviors.

For example, in real life, a person is a "class", but this is just a generic term, referring to all people. We have to find someone to play with, at this time we need to find a specific person. For example, I and Little red, we are the "human" this class of two instances.

2. How do I define a class in C #?

C # is defined by the keyword class.

Class Name {}

The class can also be decorated with an access modifier in front of it.

Access modifiers Description
Public Public access. Not subject to any restrictions.
Private Private access. This class is restricted to access by members, subclasses, and instances.
Protected Secure access. This class and subclass access is limited, and instances cannot be accessed.
Internal Internal access. Access is limited to this item and cannot be accessed by others.
protected internal Internal protection access. Limited to this item or subclass access, other inaccessible

3. Members of the class

The members of a class include fields, properties, methods, constructors, and so on. Like classes, they have their own access rights. You can also declare it as a static member of a class by using the static keyword, noting that static members are at the class-level concept and do not belong to instances of the class.

3.1 Fields

The field consists of three parts-the access modifier, the type of the field, and the field name.

public class Person

{

private string name;

public int age;

protected bool sex;

}

Of course, it can also be decorated with readonly and const, ReadOnly does not need to be initialized when defined, it can be initialized in constructors, and the const-decorated field must be initialized when a field is defined.

Classes can be decorated with static, and fields can also use static. When a field is decorated with static, it can only be accessed using the Class name. Field name.

3.2 Properties

property is an extension to a field

public class Person

{

private string name;

public string Name

{

Get{return name;}

Set{name=value;}

}

}

The property definition consists primarily of a get accessor and a set accessor. As described earlier, the Get and set properties in the IL code are compiled into two methods. Attributes are used to wrap the fields because you can better protect the fields and add more logical control code as needed. Of course, attributes can also be declared with the static keyword, which is the same as the field, at the class level, not accessed through an instance of the class, or used in static properties for non-static fields.

3.3 Methods

Method = Method Signature + code for a series of statements

public class Person

{

public void Print (string name)

{

Console.WriteLine ("AAAA");

}

}

Methods can also be decorated with the static keyword, which is also at the class level and cannot be accessed using instances of the class.

On the method, there is also a very important place, that is, method overloading, method overloading refers to the class can be defined as multiple names but different methods of signature methods, where the method signature refers to the method's parameter order, The parameter type and number are different (Warning: The return value type of the method is not part of the method signature).

public class Person

{

public void Print (string name) {}

public void Print (int age) {}

}

3.4 Constructors

A constructor is an instance object that is used to create a class. When the constructor is called to create an object, the constructor allocates memory space for the object and initializes the members of the class. There are two types of constructors: instance constructors and static constructors.

(1) Instance constructors

Typically in a program, you use the New keyword to create an object. New creates a procedure that invokes an instance constructor to initialize all instance members in a class.

For example, the person class above does not show the write instance constructor, but the C # compiler will help us automatically generate an instance constructor for the empty default lunch for the function body.

Constructors have the following characteristics:

    • Constructors can perform method overloads.
    • If you do not define a constructor for the class display, the C # compiler will help us generate an instance constructor for the empty default lunch for the function body.
    • You can specify an access level for instance constructors, which can be decorated with public, protected, and private modifiers.
    • The constructor must have the same name as the class, and no return type is allowed.

(2) Static constructors

A static constructor is used to initialize a static member of a class, and the CLR automatically calls the static constructor before the first instance is created or any static members are referenced.

Static constructors have the following characteristics:

    • Static constructors cannot use any access modifiers.
    • A static constructor cannot have any parameters.
    • The static constructor is executed only once.
    • You cannot call a static constructor directly.
    • In programs, programmers cannot control the timing of static constructors.

3.5 Destructors

Destructors are used to dispose of the managed and unmanaged resources used by the class instance before the class is destroyed. A destructor is actually a finalize method that implicitly invokes the base class object.

Class Person

{

~person ()

{

Console.WriteLine ("Destructor is called");

}

}

The destructor code above will be converted to the following code by the compiler:

protected override void Finalize ()

{

Try{console.writeline ("destructor is called");}

Finally{base. Finalize ();}

}

The following points must be noted when defining destructors:

    • Destructors cannot be defined in structs, only destructors are used on classes.
    • A class can have only one destructor.
    • Destructors cannot be inherited or overloaded.
    • The destructor is not displayed, and the destructor is automatically called by the garbage collector.
    • Destructors have neither modifiers nor parameters.

3.6 Indexer

An indexer is defined like a property, and also has a get accessor and a set accessor.

[modifier] Data type this [indexed type index]

{

get{//returns an element of an array in a class;}

set{//assigning values to array elements in a class;}

}

This indicates that an array member of the class object is being manipulated

4. Instantiation of Class

As I said earlier, to get an instance object of a class, you must first declare a variable of that class type, and then use the new operator followed by the instance constructor of the class to complete the instantiation. The instantiated object of a class is the materialization of the class.

It is important to note that only classes that contain instance constructors can be instantiated, and instance constructors cannot be defined in static classes.

5. The difference between class and structure

    • The syntactic difference is that the class is defined using the keyword class, and the struct is using a keyword struct.
    • Declaring field fields cannot be initialized in structs, but classes can.
    • If no flavor class displays the constructor, the C # compiler automatically generates an instance constructor with no parameters. struct, the implicit constructor is always present, regardless of whether the constructor is explicitly defined.
    • Constructors that do not have parameters defined in the struct cannot be displayed.
    • In a struct's constructor, you must assign a value to all the fields in the struct body.
    • Creating a struct object can be impractical for the new keyword, but there is no initial value for the field in the struct object, and the class must use the new keyword to create the object.
    • Structs cannot inherit structs or classes, but interfaces can be implemented, and classes can inherit classes but cannot inherit structs, which can also implement interfaces.
    • A class is a reference type, whereas a struct is a value type.
    • Structs cannot define destructors, and classes can have destructors.
    • Structs cannot be modified with the abstract and sealed keywords, and classes can.

Feeling this very very foundation, I am also thinking in the end whether to write, later I decided to write down. Lofty high-rise floor, coupled with technical updates are fast, but the foundation, you can status quo.

Speaking of classes in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.