АвтоАвтоматизацияАрхитектураАстрономияАудитБиологияБухгалтерияВоенное делоГенетикаГеографияГеологияГосударствоДомДругоеЖурналистика и СМИИзобретательствоИностранные языкиИнформатикаИскусствоИсторияКомпьютерыКулинарияКультураЛексикологияЛитератураЛогикаМаркетингМатематикаМашиностроениеМедицинаМенеджментМеталлы и СваркаМеханикаМузыкаНаселениеОбразованиеОхрана безопасности жизниОхрана ТрудаПедагогикаПолитикаПравоПриборостроениеПрограммированиеПроизводствоПромышленностьПсихологияРадиоРегилияСвязьСоциологияСпортСтандартизацияСтроительствоТехнологииТорговляТуризмФизикаФизиологияФилософияФинансыХимияХозяйствоЦеннообразованиеЧерчениеЭкологияЭконометрикаЭкономикаЭлектроникаЮриспунденкция

Типы данных со значением null

Читайте также:
  1. Cбор и подготовка данных
  2. II. Работа в базе данных Microsoft Access
  3. А4. Знание о файловой системе организации данных
  4. Автоматическое управление памятью ссылочных данных
  5. Алфавит языка и типы данных
  6. Анализ данных интервью
  7. Анализ данных с помощью сводных таблиц
  8. Анализ и интерпретация данных, полученных в ходе эксперементальной работы.
  9. Анализ собранных данных
  10. Архитектуры процессоров по разделению памяти данных и команд (Архитектура фон Неймана, Гарвардская архитектура).
  11. Библиографические базы данных имеют ряд недостатков. Что к ним не относится?
  12. В12. Поиск информации в базе данных по сформулированному условию

A nullable type can represent all values of its underlying type plus an additional null value. A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable<T>, and the two forms can be used interchangeably.

 

A non-nullable value type conversely is any value type other than System.Nullable<T> and its shorthand T? (for any T), plus any type parameter that is constrained to be a non-nullable value type (that is, any type parameter with a struct constraint). The System.Nullable<T> type specifies the value type constraint for T, which means that the underlying type of a nullable type can be any non-nullable value type. The underlying type of a nullable type cannot be a nullable type or a reference type. For example, int?? and string? are invalid types.

 

An instance of a nullable type T? has two public read-only properties:

· A HasValue property of type bool

· A Value property of type T

An instance for which HasValue is true is said to be non-null. A non-null instance contains a known value and Value returns that value.

An instance for which HasValue is false is said to be null. A null instance has an undefined value. Attempting to read the Value of a null instance causes a System.InvalidOperationException to be thrown. The process of accessing the Value property of a nullable instance is referred to as unwrapping.

In addition to the default constructor, every nullable type T? has a public constructor that takes a single argument of type T. Given a value x of type T, a constructor invocation of the form

new T?(x)

creates a non-null instance of T? for which the Value property is x. The process of creating a non-null instance of a nullable type for a given value is referred to as wrapping.

Implicit conversions are available from the null literal to T? and from T to T?

· For a nullable-type the default value is an instance for which the HasValue property is false and the Value property is undefined. The default value is also known as the null value of the nullable type.


 

Классы в языке C#. Отличие структур (записей) в языке C# от классов. Поля. Методы. Конструкторы и деструкторы. Свойства. Индексаторы. Атрибуты доступа. Сборки. Пространства имен. Частично определяемые классы и их назначение.

 

Классы в языке C#

 

Classes are the most fundamental of C#’s types. A class is a data structure that combines state (fields) and actions (methods and other function members) in a single unit. A class provides a definition for dynamically created instances of the class, also known as objects. Classes support inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes.

New classes are created using class declarations. A class declaration starts with a header that specifies the attributes and modifiers of the class, the name of the class, the base class (if given), and the interfaces implemented by the class. The header is followed by the class body, which consists of a list of member declarations written between the delimiters { and }.

The following is a declaration of a simple class named Point:

 

public class Point
{
public int x, y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

Instances of classes are created using the new operator, which allocates memory for a new instance, invokes a constructor to initialize the instance, and returns a reference to the instance.

 

Point p1 = new Point(0, 0);

The memory occupied by an object is automatically reclaimed when the object is no longer in use. It is neither necessary nor possible to explicitly deallocate objects in C#.

 

The members of a class are either static members or instance members. Static members belong to classes, and instance members belong to objects (instances of classes).

 

The following table provides an overview of the kinds of members a class can contain.

 

Member Description
Constants Constant values associated with the class
Fields Variables of the class
Methods Computations and actions that can be performed by the class
Properties Actions associated with reading and writing named properties of the class
Indexers Actions associated with indexing instances of the class like an array
Events Notifications that can be generated by the class
Operators Conversions and expression operators supported by the class
Constructors Actions required to initialize instances of the class or the class itself
Destructors Actions to perform before instances of the class are permanently discarded
Types Nested types declared by the class

 

A class declaration may specify a base class by following the class name and type parameters with a colon and the name of the base class. Omitting a base class specification is the same as deriving from type object.

 

public class Point3D: Point
{
public int z;

public Point3D(int x, int y, int z): base(x, y)

{
this.z = z;
}
}

 

A class inherits the members of its base class. Inheritance means that a class implicitly contains all members of its base class, except for the instance and static constructors, and the destructors of the base class. A derived class can add new members to those it inherits, but it cannot remove the definition of an inherited member.

 

An implicit conversion exists from a class type to any of its base class types. Therefore, a variable of a class type can reference an instance of that class or an instance of any derived class.

 

Point a = new Point(10, 20);
Point b = new Point3D(10, 20, 30);

 

public class List<T> {
const int defaultCapacity = 4; Constant
T[] items; int count; Fields
public List(int capacity = defaultCapacity) { items = new T[capacity]; } Constructors
public int Count { get { return count; } } public int Capacity { get { return items.Length; } set { if (value < count) value = count; if (value!= items.Length) { T[] newItems = new T[value]; Array.Copy(items, 0, newItems, 0, count); items = newItems; } } } Properties

 

public T this[int index] { get { return items[index]; } set { items[index] = value; OnChanged(); } } Indexer
public void Add(T item) { if (count == Capacity) Capacity = count * 2; items[count] = item; count++; OnChanged(); } protected virtual void OnChanged() { if (Changed!= null) Changed(this, EventArgs.Empty); } public override bool Equals(object other) { return Equals(this, other as List<T>); } static bool Equals(List<T> a, List<T> b) { if (a == null) return b == null; if (b == null || a.count!= b.count) return false; for (int i = 0; i < a.count; i++) { if (!object.Equals(a.items[i], b.items[i])) { return false; } } return true; } Methods
public event EventHandler Changed; Event
public static bool operator ==(List<T> a, List<T> b) { return Equals(a, b); } public static bool operator!=(List<T> a, List<T> b) { return!Equals(a, b); } Operators
}

An operator is a member that defines the meaning of applying a particular expression operator to instances of a class. Three kinds of operators can be defined: unary operators, binary operators, and conversion operators. All operators must be declared as public and static.

The List<T> class declares two operators, operator == and operator!=, and thus gives new meaning to expressions that apply those operators to List instances.


1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |

Поиск по сайту:



Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Студалл.Орг (0.004 сек.)