简体   繁体   中英

How to use the constraint 'delegate'

C# now allows delegate constraints in generics. As I was trying to learn the new feature, I could not come with a single practical way of using it. As others have been asking for this feature for years, I am obviously missing the point here.

public class Test<TDelegate> where TDelegate : Delegate
{
    readonly TDelegate fd; // no way to call this 
    public event TD Evt; // not even legal
}

How does a class do anything useful with a generic parameter that is a delegate?

All you have to do is:

public static void Foo<T>(T t) where T : System.Delegate
{
    t.DynamicInvoke();
}

For some reason, the normal Invoke() isn't a valid method that can be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM