泛型委托 (Visual C++)
可以使用委托的泛型类型参数。 有关委托的更多信息,请 委托(C++ 组件扩展)参见。
[attributes]
generic < [class | typename] type-parameter-identifiers >
[type-parameter-constraints-clauses]
[accessibility-modifiers] delegate result-type identifier
([formal-parameters]);
参数
attributes(可选)
附加描述性信息。 有关特性和特性类的更多信息,请参见属性。类型参数标识符
逗号分隔列表该类型的参数标识符。type-parameter-constraints-clauses
带有指定的窗体 泛型类型参数的约束 (C++/CLI)可访问性修饰符 (可选)
可访问性修饰符 (即。 public, private)。结果类型
委托的返回类型。标识符
委托的名称。正式参数 (可选)
参数列表委托。
示例
委托类型参数指定在委托对象创建的点。 委托和方法与它必须具有相同的签名。 下面是泛型委托声明的示例。
// generics_generic_delegate1.cpp
// compile with: /clr /c
generic < class ItemType>
delegate ItemType GenDelegate(ItemType p1, ItemType% p2);
下面的示例演示了
不能使用不同的构造类型的同一委托对象。 创建不同类型的变体委托对象。
泛型委托可与泛型方法。
当泛型方法调用,但没有指定类型变量,编译器尝试推断调用的类型参数。
// generics_generic_delegate2.cpp
// compile with: /clr
generic < class ItemType>
delegate ItemType GenDelegate(ItemType p1, ItemType% p2);
generic < class ItemType>
ref struct MyGenClass {
ItemType MyMethod(ItemType i, ItemType % j) {
return ItemType();
}
};
ref struct MyClass {
generic < class ItemType>
static ItemType MyStaticMethod(ItemType i, ItemType % j) {
return ItemType();
}
};
int main() {
MyGenClass<int> ^ myObj1 = gcnew MyGenClass<int>();
MyGenClass<double> ^ myObj2 = gcnew MyGenClass<double>();
GenDelegate<int>^ myDelegate1 =
gcnew GenDelegate<int>(myObj1, &MyGenClass<int>::MyMethod);
GenDelegate<double>^ myDelegate2 =
gcnew GenDelegate<double>(myObj2, &MyGenClass<double>::MyMethod);
GenDelegate<int>^ myDelegate =
gcnew GenDelegate<int>(&MyClass::MyStaticMethod<int>);
}
下面的示例声明一个泛型委托 GenDelegate<ItemType>,通过将然后实例化到使用类型参数 ItemType的方法 MyMethod 。 委托 (整型和二进制文件) 的两个实例创建并调用。
// generics_generic_delegate.cpp
// compile with: /clr
using namespace System;
// declare generic delegate
generic <typename ItemType>
delegate ItemType GenDelegate (ItemType p1, ItemType% p2);
// Declare a generic class:
generic <typename ItemType>
ref class MyGenClass {
public:
ItemType MyMethod(ItemType p1, ItemType% p2) {
p2 = p1;
return p1;
}
};
int main() {
int i = 0, j = 0;
double m = 0.0, n = 0.0;
MyGenClass<int>^ myObj1 = gcnew MyGenClass<int>();
MyGenClass<double>^ myObj2 = gcnew MyGenClass<double>();
// Instantiate a delegate using int.
GenDelegate<int>^ MyDelegate1 =
gcnew GenDelegate<int>(myObj1, &MyGenClass<int>::MyMethod);
// Invoke the integer delegate using MyMethod.
i = MyDelegate1(123, j);
Console::WriteLine(
"Invoking the integer delegate: i = {0}, j = {1}", i, j);
// Instantiate a delegate using double.
GenDelegate<double>^ MyDelegate2 =
gcnew GenDelegate<double>(myObj2, &MyGenClass<double>::MyMethod);
// Invoke the integer delegate using MyMethod.
m = MyDelegate2(0.123, n);
Console::WriteLine(
"Invoking the double delegate: m = {0}, n = {1}", m, n);
}