Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Создание обобщенных интерфейсов

Перегрузка операторов преобразования типа | Специализации шаблонов | Assert срабатывает только в режиме Debug | Потоки ввода-вывода | Автоматическое управление памятью ссылочных данных | Упаковка и разупаковка данных | Типы данных со значением null | Конструкторы и деструкторы | Частично определяемые классы и их назначение | Механизм вызова событий |


Читайте также:
  1. A. Создание персонажей
  2. I. Создание визитной карточки
  3. I. Создание информационного трехстраничного буклета
  4. I. Создание Энергетического и Духовного Тел
  5. MS PowerPoint. Создание слайда с диаграммой и таблицей
  6. MS PowerPoint. Создание управляющих кнопок
  7. VBA7. Сортировка чисел в столбце по возрастанию или убыванию с созданием формы и панели инструментов с кнопкой

Вы уже видели при рассмотрении пространства имен System.Collections.Generic, что обобщенные интерфейсы в C# также допустимы (например, IEnumerable<T>). Вы, конечно, можете определить свои собственные обобщенные интерфейсы (как с ограничениями, так и без ограничений). Предположим, что нужно определить интерфейс, который сможет выполнять бинарные операции с параметрами обобщенного типа.

public interface IBinaryOperations<T>{ T Add(T arg1, T arg2); T Subtract(T arg1, T arg2); T Multiply(T arg1, T arg2); T Divide(T arg1, T arg2); }

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

public class BasicMath: IBinaryOperations<int>{ public int Add(int arg1, int arg2) { return arg1 + arg2; } public int Subtract(int arg1, int arg2) { return arg1 - arg2; } public int Multiply(int arg1, int arg2) { return arg1 * arg2; } public int Divide(int arg1, int arg2) { return arg1 / arg2; } }

После этого вы можете использовать BasicMath.

Если вместо этого требуется создать класс BasicMath, действующий на числа с плавающим десятичным разделителем, можно конкретизировать параметр типа так.

public class BasicMath: IBinaryOperations<double>{ public double Add(double arg1, double arg2) { return arg1 + arg2; }...}

 

 

C# Generics and C++ templates are both language features that provide support for parameterized types. However, there are many differences between the two.

 

At the syntax level, C# generics are a simpler approach to parameterized types without the complexity of C++ templates. In addition, C# does not attempt to provide all of the functionality that C++ templates provide. At the implementation level, the primary difference is that C# generic type substitutions are performed at runtime and generic type information is thereby preserved for instantiated objects.

 

The following are the key differences between C# Generics and C++ templates:

· C# generics do not provide the same amount of flexibility as C++ templates. For example, it is not possible to call arithmetic operators in a C# generic class, although it is possible to call user defined operators.

· C# does not allow non-type template parameters, such as template C<int i> {}.

· C# does not support explicit specialization; that is, a custom implementation of a template for a specific type.

· C# does not support partial specialization: a custom implementation for a subset of the type arguments.

· C# does not allow the type parameter to be used as the base class for the generic type.

· C# does not allow type parameters to have default types.

· In C#, a generic type parameter cannot itself be a generic, although constructed types can be used as generics. C++ does allow template parameters.

· C++ allows code that might not be valid for all type parameters in the template, which is then checked for the specific type used as the type parameter. C# requires code in a class to be written in such a way that it will work with any type that satisfies the constraints. For example, in C++ it is possible to write a function that uses the arithmetic operators + and - on objects of the type parameter, which will produce an error at the time of instantiation of the template with a type that does not support these operators. C# disallows this; the only language constructs allowed are those that can be deduced from the constraints.


Дата добавления: 2015-11-16; просмотров: 95 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Создание пользовательских обобщенных коллекций| Установка ограничений на параметры обобщенных классов

mybiblioteka.su - 2015-2024 год. (0.006 сек.)