C #---properties and fields

Source: Internet
Author: User

Variables in C #

Memory: User stores running program Data RAM (random memory) data loss after power loss

Variables represent this piece of memory space, and we can store/fetch data to memory through variable names. There is no need for us to memorize complex memory addresses.

First request a piece of memory space to the computer, consider the data type to the memory side, request a piece of memory space syntax for memory:

int number;//application to open up a piece of memory space

number=1000;//put 1000 in number.

Console.WriteLine (number);

Console.readkey ();

Variables can be in class, declared in methods ...

Field

A field is any type of variable that is declared directly in the class or structure. A field is a "member" of its containing type. (Simply put, a field is a variable that appears directly in a class or struct)

A class or struct can have instance fields or static fields. or both. Instance fields are specific to an instance of a type. If you have a class T and an instance field F, you can create two objects of type T and modify each

The value of F in the object, which does not affect the value in another object. In contrast, a static field belongs to the class itself and is shared across all instances of the class. Changes made from instance A are immediately rendered on instances B and C (if they access the field)

You should typically use fields only for variables that have private or protected accessibility. The data that your class exposes to client code should be provided through methods, properties, indexers. By using these constructs to indirectly access internal fields, you can

Invalid input value provides protection. A private field that stores data exposed by a public property is called a backing store or support field.

Fields typically store such data: The data must be accessible to multiple class methods, and its storage period must be longer than the lifetime of any single method. For example, a class that represents a calendar date may have 3 integer fields: one for the month, one for the table

Date, and one representing the year. If a variable is used only within a range of methods then it should be declared as a local variable within the scope of the method body itself.

Declare these fields in the class block by specifying the access level of the field, and then specifying the field's type, in the name of the specified field. For example:

public class Calendarentry

{

Private fields

Private DateTime date;

Public fields (generally not recommended)

public string Day;

Public properties provide security for the date field

Public DateTime Date

{

Get{return date;}

Set

{

Set reasonable boundaries for possible birth dates

if (value. Year>1900&&value. Year<=datetime.today.year)

{

Date=value;

}

Else

throw new ArgumentOutOfRangeException ();

}

}

Public methods provide security for the date field

For example: birthday. SetDate ("1975,6,30");

public void SetDate (string datestring)

{

DateTime Dt=convert.todatetime (datestring);

Set reasonable boundaries for birth dates

if (dt. Year>1900&&dt. Year<=datetime.today.year)

{

DATE=DT;

}

Else

throw new ArgumentOutOfRangeException ();

}

Public TimeSpan Gettimespan (string datestring)

{

DateTime Dt=convert.todatetime (datestring);

if (Dt!=null&&dt. Ticks<date. Ticks)

{

return DATE-DT;

}

Else

throw new ArgumentOutOfRangeException ();

}

}

To access a field in an object, add a period after the object name, and then add the name of the field, such as Objectname.fieldname. For example:

Calendarentry birthday=new calendarentry ();

Bitrhday.day= "Saturday";

You can use the assignment operator to specify an initial value for a field when declaring a field. For example, to automatically assign the Monday to day field, you need to declare day, as shown in the following example:

public class Calendardatewithinitialization

{

public string day= "Monday";

}

The initialization of a field is immediately before the constructor of the calling object instance. If the constructor assigns a value to a field, the value overrides any value given during the field declaration

Description: A field initializer cannot reference another instance field.

Property

Attributes are the basic concepts of object-oriented programming, providing access encapsulation of private fields, and the operation of a readable writable property in C # with the get and set accessor methods .

Provides secure and flexible data access encapsulation. (This corresponds to the above field description)

A property is a member that provides a flexible mechanism to read, write, or calculate the value of a private field. You can use properties as you would with public data members, but they are a special method called accessors. This makes it easy to access the data and also helps to improve the method

Security and flexibility.

Example 1:

public class MyProperty

{

Defining fields

private string name;

private int age;

Defining attributes, implementing encapsulation of the Name field

public string Name

{

Set{name=value;}

Get

{

if (name==null)

return string. Empty;

Else

return name;

}

}

Defining attributes, implementing encapsulation of the Age field

Adding scope controls to fields

public int Age

{

Get{return age;}

Set

{

if (value>0) && (value<150)

{

Age=value;

}

Else

{

throw new Exception ("Not a real age");

}

}

}

}

public class MyTest

{

public static void Main (string[] args)

{

MyProperty myproperty=new MyProperty ();

Triggering a set accessor

Myproperty.name= "Anytao"

Trigger get accessor

Console.WriteLine (Myproperty.name);

}

}

Example 2:

In this example, the TimePeriod class stores a time period. Internally, the class stores the time in seconds, but the client uses a property named hours to specify the time in hours. The accessor for the Hours property performs a conversion between hours and seconds.

Class TimePeriod

{

private double seconds;

Public double Hours

{

Get{return second/3600;}

SET{SECOND=VALUE*3600}

}

}

Class Program

{

static void Main ()

{

TimePeriod t=new timeperiod ();

Set the Hours property to call the Set method automatically

t.hours=24;

Get the Hours property, call the Get method automatically

System.Console.WriteLine ("Time in Hours:" +t.hours);

}

}

Properties Overview

Property enables a class to get and set values in a public way, while hiding the implementation or validation code.

The Get property accessor is used to return a property value, and a set accessor is used to assign a new value. These accessors can have different access levels. For more information, see restricting accessor Accessibility (C # Programming Guide).

The value keyword is used to define the values that are assigned by the set accessor function.

Properties that do not implement set accessor functions are read-only.

For simple properties that do not require any custom accessor code, consider selecting properties that use auto-implementation. For more information, see Auto-implemented Properties (C # Programming Guide)

C #---properties and fields

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.