What are generic delegates in C#?

WBOY
Release: 2023-08-26 13:49:05
forward
686 people have browsed it

C# 中的泛型委托是什么?

With generic delegates, you do not need to define a delegate statement. They are defined in the system namespace.

You can define a generic delegate using type parameters. For example -

delegate T myDelegete<T>(T n);
Copy after login

Example

The following example shows how to create a generic delegate in 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();
      }
   }
}
Copy after login

The above is the detailed content of What are generic delegates in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!