
使用通用委托,您不需要定义委托语句。它们在系统命名空间中定义。
您可以使用类型参数定义通用委托。例如 -
delegate T myDelegete<T>(T n);
以下示例展示了如何在 C# 中创建通用委托 -
using System;
using System.Collections.Generic;
delegate T myDelegete<T>(T n);
namespace GenericDelegateAppl {
class TestDelegate {
static int num = 5;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(50);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(10);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}以上就是C# 中的泛型委托是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号