gpt4 book ai didi

c# - `where T : Delegate` 还是 `where T : MulticastDelegate` ?

转载 作者:行者123 更新时间:2023-12-01 19:15:46 36 4
gpt4 key购买 nike

C# 7.3 添加了 support用于将泛型类型参数约束为委托(delegate)类型。

public class UsingDelegate<T> where T : System.Delegate { }
public class Multicaster<T> where T : System.MulticastDelegate { }

这可能是微不足道的,但是 where T : System.Delegatewhere T : System.MulticastDelegate 之间有什么实际区别吗? Microsoft 文档中未记录此内容。

最佳答案

我们无法实例化 DelegateMulticastDelegate 类,因为这些类是抽象:

 public abstract class Delegate : ICloneable, ISerializable { ... }

public abstract class MulticastDelegate : Delegate { ... }

使用委托(delegate)的主要方式是 delegate 关键字。当我们使用 C# 语言关键字 delegate 声明委托(delegate)类型时,C# 编译器会创建从 MulticastDelegate 派生的类的实例。

The reason of why C# compiler creates instances of a class derived from MulticastDelegate is:

This design has its roots in the first release of C# and .NET. One goal for the design team was to ensure that the language enforced type safety when using delegates. That meant ensuring that delegates were invoked with the right type and number of arguments. And, that any return type was correctly indicated at compile time. Delegates were part of the 1.0 .NET release, which was before generics.

The best way to enforce this type safety was for the compiler to create the concrete delegate classes that represented the method signature being used.

Even though you cannot create derived classes directly, you will use the methods defined on these classes.

可以看出,委托(delegate)是 1.0 .NET 版本的一部分,它早于泛型,因此可以得出约束 where T : System.Delegate { } 由于历史原因而存在于 C# 7.3 中,通过创建表示所使用的方法签名的具体委托(delegate)类来强制编译器的类型安全。

关于c# - `where T : Delegate` 还是 `where T : MulticastDelegate` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59892041/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com