Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Переопределение метода ToString

Каждый объект в языке C# наследует метод ToString, который возвращает строковое представление данного объекта. Например, все переменные типа int имеют метод ToString, который позволяет им возвращать содержимое этой переменной в виде строки:

int x = 42;

string strx = x.ToString();

System.Console.WriteLine(strx);

При создании пользовательского класса или структуры необходимо переопределить метод ToString, чтобы передать информацию о типе клиентскому коду.

Примечание о безопасности.

При принятии решения относительно того, какая информация должна будет предоставляться посредством этого метода, подумайте, будет ли создаваемый класс или структура когда-либо использоваться ненадежным кодом. Постарайтесь не предоставлять информацию, которая может быть использована вредоносным кодом.

Порядок переопределения метода OnString в классе или структуре

  1. Объявите метод ToString со следующими модификаторами и типом возвращаемого значения:

    public override string ToString(){}

  2. Реализуйте этот метод таким образом, чтобы он возвращал строку.

Приведенный ниже пример возвращает не только имя класса, но и специфические данные для конкретного экземпляра класса. Обратите внимание, что он также использует метод ToString в переменной age для преобразования типа int в строку, которая может служить выходными данными.

----

Interfaces

Interfaces are defined by using the interface keyword. For example:

interface IComparable

{

int CompareTo(object obj);

}

Interfaces describe a group of related functionalities that can belong to any class or struct. Interfaces can consist of methods, properties, events, indexers, or any combination of those four member types. An interface cannot contain fields. Interfaces members are automatically public.

Classes and structs can inherit from interfaces in a manner similar to how classes can inherit a base class or struct, with two exceptions:

  • A class or struct can inherit more than one interface.

  • When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations. For example:

public class Minivan : Car, IComparable

{

public int CompareTo(object obj)

{

//implementation of CompareTo

return 0; //if the Minivans are equal

}

}

To implement an interface member, the corresponding member on the class must be public, non-static, and have the same name and signature as the interface member. Properties and indexers on a class can define extra accessors for a property or indexer defined on an interface. For example, an interface may declare a property with a get accessor, but the class implementing the interface can declare the same property with both a get and set accessor. However, if the property or indexer uses explicit implementation, the accessors must match.