gpt4 book ai didi

c# - C# 中的特殊 Method 方法定义

转载 作者:行者123 更新时间:2023-12-03 07:21:52 25 4
gpt4 key购买 nike

我正在使用 C#。我从未见过这样的方法声明

private AuthorizationContext GetAuthorizationContext<TController>() where TController : ControllerBase, new()
{
}

谁能帮我解释一下这是什么意思。我对泛型类有清晰的想法。我的查询部分是“where TController : ControllerBase, new()”

最佳答案

这是一个类型约束。它指定泛型类型 (TController) 必须满足的某些条件。在这种情况下,它必须从 ControllerBase 派生并具有无参数构造函数。

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

有时,将任何类型用作泛型类型参数都是没有意义的。例如,如果我想确保类型 T 具有某些方法,我可以强制它实现给定的接口(interface)。这提供了额外的类型安全和编译时检查。

关于c# - C# 中的特殊 Method 方法定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22802099/

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