[C #] delegation and method group

Source: Internet
Author: User

When writing delegation-related code, especially generic delegation-related code, you may encounter the following problem: Define a delegation type: [csharp] public delegate void TestDelegate <T> (T arg); defines a test class and Method: [csharp] public class TestClass {public void TestFunc4Delegate (int arg) {} public void TestFunc1 (Delegate dele) {} public void TestFunc2 <T> (TestDelegate <T> dele) {}} code used for testing: [csharp] 1. testClass tc = new TestClass (); 2. tc. testFunc1 (tc. testFunc4Delegate); 3. tc. testFunc2 (tc. testFunc4Del Egate); then, you will find that the code used in the above test has a compilation error. The compilation error in the second row is "The method group cannot be converted to System. delegate ". The third line of compilation error is" TestClass cannot be exported from usage. testFunc2 <T> (TestDelegate <T>) type parameter ". The core issue for the above errors is the "method group. "Method group" is a compiler concept. Because C # supports method overloading, methods with the same name may have multiple implementation methods for overloading, all the methods with the same names are combined into a method group. In the above example, tc. TestFunc4Delegate actually points to the method group named Test4Delegate. Although the class definition above does not overload Test4Delegate, it is still a method group. Since it is a method group, the problem arises-you cannot determine which overload of the method group is required. The compiler cannot determine which delegate subtype to use to create a delegate instance because it cannot be determined, and the correct type of the generic type cannot be deduced. To enable the call in the preceding example to be compiled, you must specify a qualified type, as shown in the following figure: [csharp] tc. testFunc1 (TestDelegate <int>) tc. testFunc4Delegate); tc. testFunc2 <int> (tc. test4Delegate );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.