简体   繁体   English

如何使用约束“委托”

[英]How to use the constraint 'delegate'

C# now allows delegate constraints in generics. C#现在允许泛型中的委托约束。 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. 由于某些原因,普通的Invoke()不是可以使用的有效方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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