CATEGORII DOCUMENTE |
Class declarations define new reference types. A class can inherit from another class, and can implement interfaces.
Class members can include constants, fields, methods, properties, indexers, events, operators, instance constructors, static constructors, destructors, and nested type declarations. Each member has an associated accessibility, which controls the regions of program text that are able to access the member. There are five possible forms of accessibility. These are summarized in the table below.
Form |
Intuitive meaning |
public |
Access not limited |
protected |
Access limited to the containing class or types derived from the containing class |
internal |
Access limited to this program |
protected internal |
Access limited to this program or types derived from the containing class |
private |
Access limited to the containing type |
The example
using System;
class
MyClass
public MyClass(int value)
~MyClass()
public const int MyConst = 12;
public int MyField = 34;
public void MyMethod()
public int MyProperty
set
}
public int this[int index]
set ]
= ', index, value);
}
}
public event EventHandler MyEvent;
public static MyClass operator+(MyClass a, MyClass b)
internal class MyNestedClass
}
shows a class that contains each kind of member. The example
class
Test
', MyClass.MyConst);
// Field usage
a.MyField++;
Console.WriteLine('a.MyField
= ', a.MyField);
// Method usage
a.MyMethod();
// Property usage
a.MyProperty++;
Console.WriteLine('a.MyProperty
= ', a.MyProperty);
// Indexer usage
a[3] = a[1] = a[2];
Console.WriteLine('a[3] =
', a[3]);
// Event usage
a.MyEvent += new
EventHandler(MyHandler);
// Overloaded operator usage
MyClass c = a + b;
}
static void MyHandler(object sender, EventArgs e)
internal class MyNestedClass
}
shows uses of these members.
A constant is a class member that represents a constant value: a value that can be computed at compile-time. Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies. The rules governing constant expressions are defined in constant expression 7.15. The example
class
Constants
shows a class named Constants that has two public constants.
Even though constants are considered static members, a constant declaration neither requires nor allows the static modifier. Constants can be accessed through the class, as in
class
Test
{
static void
Console.WriteLine(',
', Constants.A, Constants.B);
}
}
which prints out the values of Constants.A and Constants.B.
A field is a member that represents a variable associated with an object or class. The example
class
Color
}
shows a Color class that has internal instance fields named redPart, bluePart, and greenPart. Fields can also be static, as shown in the example
class
Color
which shows static fields for Red, Blue, Green, and White.
Static fields are not a perfect match for this scenario. The fields are initialized at some point before they are used, but after this initialization there is nothing to stop a client from changing them. Such a modification could cause unpredictable errors in other programs that use Color and assume that the values do not change. Readonly fields can be used to prevent such problems. Assignments to a readonly field can only occur as part of the declaration, or in an instance or static constructor in the same class. A static readonly field can be assigned in a static constructor, and a non-static readonly field can be assigned in an instance constructor. Thus, the Color class can be enhanced by adding the readonly modifier to the static fields:
class
Color
public static readonly Color Red = new
Color(0xFF, 0, 0);
public static readonly Color Blue =
new Color(0, 0xFF, 0);
public static readonly Color Green =
new Color(0, 0, 0xFF);
public static readonly Color White =
new Color(0xFF, 0xFF, 0xFF);
}
A method is a member that implements a computation or action that can be performed by an object or class. Methods have a list of formal parameters (which may be empty), a return value (or void), and are either static or non-static. Static methods are accessed through the class. Non-static methods, which are also called instance methods, are accessed through instances of the class. The example
using System;
public
class Stack
public static Stack Flip(Stack s)
public object Pop()
public void Push(object o)
public override string ToString()
}
class
Test
}
shows a Stack that has several static methods (Clone and Flip) and several instance methods (Push, Pop, and ToString).
Methods can be overloaded, which means that multiple methods may have the same name so long as they have unique signatures. The signature of a method consists of the name of the method and the number, modifiers, and types of its formal parameters. The signature of a method does not include the return type. The example
class
Test
static void F(object o)
static void F(int value)
static void F(ref int value)
static void F(out int value)
static void F(int a, int b)
static void F(int[] values)
static void Main() );
}
}
shows a class with a number of methods named F. The output of the program is
F()
F(int)
F(ref int)
F(out int)
F(object)
F(int, int)
F(int[])
A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written.
Properties are defined with property declarations. The first part of a property declaration looks quite similar to a field declaration. The second part includes a get accessor and/or a set accessor. In the example below, the Button class defines a Caption property.
public
class Button
set
}
}
Properties that can be both read and written, such as Caption, include both get and set accessors. The get accessor is called when the property's value is read; the set accessor is called when the property's value is written. In a set accessor, the new value for the property is made available via an implicit parameter named value.
The declaration of properties is real value of properties is seen when they are used. For example, the Caption property can be read and written in the same way that fields can be read and written:
Button b = new Button();
b.Caption = 'ABC'; // set; causes repaint
string s = b.Caption; // get
b.Caption += 'DEF"; // get & set; causes repaint
An event is a member that enables an object or class to provide notifications. A class defines an event by providing an event declaration, which resembles a field declaration, though with an added event keyword, and an optional set of event accessors. The type of this declaration must be a delegate type.
An instance of a delegate type encapsulates one or more callable entities. For instance methods, a callable entity consists of an instance and a method on that instance. For static methods, a callable entity consists of just a method. Given a delegate instance and an appropriate set of arguments, one can invoke all of that delegate instance's methods with that set of arguments.
In the example
public delegate void EventHandler(object sender, System.EventArgs e);
public
class Button
}
the Button class defines a Click event of type EventHandler. Inside the Button class, the Click member corresponds exactly to a private field of type EventHandler. However, outside the Button class, the Click member can only be used on the left hand side of the += and -= operators. The += operator adds a handler for the event, and the -= operator removes a handler for the event. The example
using System;
public
class Form1
Button Button1 = new Button();
void Button1_Click(object sender, EventArgs e)
public void Disconnect()
}
shows a Form1 class that adds Button1_Click as an event handler for Button1's Click event. In the Disconnect method, the event handler is removed.
For a simple event declaration such as
public event EventHandler Click;
the compiler automatically provides the implementation underlying the += and -= operators.
An implementer who wants more control can get it by explicitly providing add and remove accessors. For example, the Button class could be rewritten as follows:
public
class Button
remove
}
}
This change has no effect on client code, but allows the Button class more implementation flexibility. For example, the event handler for Click need not be represented by a field.
An operator is a member that defines the meaning of an expression operator that can be applied to instances of the class. There are three kinds of operators that can be defined: unary operators, binary operators, and conversion operators.
The following example defines a Digit type that represents decimal digits-integral values between 0 and 9.
using System;
public
struct Digit
public Digit(int value): this((byte) value)
public static implicit operator byte(Digit d)
public static explicit operator Digit(byte b)
public static Digit operator+(Digit a, Digit b)
public static Digit operator-(Digit a, Digit b)
public static bool operator==(Digit a, Digit b)
public static bool operator!=(Digit a, Digit b)
public override bool Equals(object value)
public override int GetHashCode()
public override string ToString()
}
class
Test
{
static void Main() {
Digit a = (Digit) 5;
Digit b = (Digit) 3;
Digit plus = a + b;
Digit minus = a - b;
bool equals = (a == b);
Console.WriteLine(' +
= ', a, b, plus);
Console.WriteLine(' -
= ', a, b, minus);
Console.WriteLine(' ==
= ', a, b, equals);
}
}
The Digit type defines the following operators:
An implicit conversion operator from Digit to byte.
An explicit conversion operator from byte to Digit.
An addition operator that adds two Digit values and returns a Digit value.
A subtraction operator that subtracts one Digit value from another, and returns a Digit value.
The equality (==) and inequality (!=) operators, which compare two Digit values.
An indexer is a member that enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access.
As an example, consider the Stack class presented earlier. This class might want to expose array-like access so that it is possible to inspect or alter the items on the stack without performing unnecessary Push and Pop operations. The Stack is implemented as a linked list, but wants to provide the convenience of array access.
Indexer declarations are similar to property declarations, with the main differences being that indexers are nameless (the "name" used in the declaration is this, since this is being indexed) and that indexers include indexing parameters. The indexing parameters are provided between square brackets. The example
using System;
public
class Stack
return temp;
}
public object this[int index]
set
}
}
class
Test
}
shows an indexer for the Stack class.
An instance constructor is a member that implements the actions required to initialize an instance of a class.
The example
using System;
class
Point
public Point(double x, double y)
public static double Distance(Point a, Point b)
public override string ToString() {
return
string.Format('(, )', x, y);
}
}
class
Test
{
static void
Point a = new Point();
Point b = new Point(3, 4);
double d = Point.Distance(a,
b);
Console.WriteLine('Distance
from to is ', a, b, d);
}
}
shows a Point class that provides two public instance constructors. One instance constructor takes no arguments, and the other takes two double arguments.
If no instance constructor is supplied for a class, then an empty instance constructor with no parameters is automatically provided.
A destructor is a member that implements the actions required to destruct an instance of a class. Destructors cannot have parameters, cannot have accessibility modifiers, and cannot be called explicitly. The destructor for an instance is called automatically during garbage collection.
The example
using System;
class
Point
{
public double x, y;
public Point(double x, double y)
~Point() {
Console.WriteLine('Destructed
', this);
}
public override string ToString() {
return string.Format('(,
)', x, y);
}
}
shows a Point class with a destructor.
A static constructor is a member that implements the actions required to initialize a class. Static constructors cannot have parameters, cannot have accessibility modifiers, and cannot be called explicitly. The static constructor for a class is called automatically.
The example
using System.Data;
class
Employee
public string Name;
public decimal Salary;
}
shows an Employee class with a static constructor that initializes a static field.
Classes support single inheritance, and the type object is the ultimate base class for all classes.
The classes shown in earlier examples all implicitly derive from object. The example
class A
}
shows a class A that implicitly derives from object. The example
class B:
A
}
class
Test
}
shows a class B that derives from A. The class B inherits A's F method, and introduces a G method of its own.
Methods, properties, and indexers can be virtual, which means that their implementation can be overridden in derived classes. The example
using System;
class A
}
class B:
A
}
class
Test
}
shows a class A with a virtual method F, and a class B that overrides F. The overriding method in B contains a call, base.F(), which calls the overridden method in A.
A class can indicate that it is incomplete, and is intended only as a base class for other classes, by including the abstract modifier. Such a class is called an abstract class. An abstract class can specify abstract members-members that a non-abstract derived class must implement. The example
using System;
abstract
class A
class B:
A
}
class
Test
}
introduces an abstract method F in the abstract class A. The non-abstract class B provides an implementation for this method.
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 921
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved