How to: Override the ToString Method 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Override the ToString Method



Every object in C# inherits the ToString method, which returns a string representation of that object. For example, all variables of type int have a ToString method, which enables them to return their contents as a string:

int x = 42; string strx = x.ToString(); System.Console.WriteLine(strx);

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code.

Security Note:
When you decide what information to provide through this method, consider whether your class or struct will ever be used by untrusted code. Be careful to ensure that you do not provide any information that could be exploited by malicious code.

To override the OnString method in your class or struct

1. Declare a ToString method with the following modifiers and return type:

public override string ToString(){}

2. Implement the method so that it returns a string.

The following example returns not only the name of the class, but also the data specific to a particular instance of the class. Note that it also uses the ToString method on the age variable to covert the int to a string that can be output.

class Person { string name; int age; SampleObject(string name, int age) { this.name = name; this.age = age; } public override string ToString() { string s = age.ToString(); return "Person: " + name + " " + s; } }

Переопределение метода 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.

 


Интерфейсы

Интерфейсы определяются с помощью ключевого слова interface. Пример.

interface IComparable { int CompareTo(object obj); }

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

Классы и структуры могут быть унаследованы от интерфейсом таким же образом, как классы могут быть унаследованы от базового класса или структуры, но есть два исключения:

· Класс или структура может наследовать несколько интерфейсов.

· Когда класс или структура наследует интерфейс, наследуются только имена и подписи методов, поскольку сам интерфейс не содержит реализаций. Пример.

ß---

 

 

Для реализации члена интерфейса соответствующий член класса должен быть открытым и не статическим, он должен обладать таким же именем и подписью, как член интерфейса. Свойства и индексаторы класса могут определить дополнительные методы доступа для свойства или индексатора, определенного в интерфейсе. Например, интерфейс может объявлять свойство с методом доступа get, но класс, реализующий интерфейс, может объявлять это же свойство с методами доступа get и set. Если же свойство или индексатор использует явную реализацию, методы доступа должны совпадать.


Interfaces and interface members are abstract; interfaces do not provide a default implementation. For more information, see Abstract and Sealed Classes and Class Members.

The IComparable interface announces to the user of the object that the object can compare itself to other objects of the same type, and the user of the interface does not have to know how this is implemented.

Interfaces can inherit other interfaces. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members. For more information about virtual members, see Polymorphism.

Interfaces Overview

An interface has the following properties:

· An interface is like an abstract base class: any non-abstract type inheriting the interface must implement all its members.

· An interface cannot be instantiated directly.

· Interfaces can contain events, indexers, methods and properties.

· Interfaces contain no implementation of methods.

· Classes and structs can inherit from more than one interface.

· An interface can itself inherit from multiple interfaces.

 


Интерфейсы и члены интерфейсов являются абстрактными. Интерфейсы не имеют реализации по умолчанию. Дополнительные сведения см. в разделе Абстрактные и запечатанные классы и члены классов.

Интерфейс IComparable объявляет пользователю объекта, что объект может сравнивать себя с другими объектами такого же типа, причем пользователь интерфейса не должен знать, как именно это реализовано.

Интерфейсы могут наследовать другие интерфейсы. Класс может наследовать интерфейс несколько раз посредством наследуемых базовых классов или интерфейсов. В этом случае класс может реализовать интерфейс только один раз, если он объявляется частью нового класса. Если унаследованный интерфейс не объявлен как часть нового класса, его реализация предоставляется базовым классом, объявившим его. Базовый класс может реализовать члены интерфейса посредством виртуальных членов. В этом случае класс, наследующий интерфейс, может изменить поведение наследования путем переопределения виртуальных членов. Дополнительные сведения о виртуальных членах см. в разделе Полиморфизм.



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 170; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.218.172.249 (0.007 с.)