gpt4 book ai didi

c# - 扩展方法可以有泛型参数吗?

转载 作者:行者123 更新时间:2023-11-30 14:18:16 30 4
gpt4 key购买 nike

扩展方法可以说:列表作为参数之一吗?

public static IEnumerable<XElement> GetSequenceDescendants(this IEnumerable<XElement> elements, params List<XName> names)
{
//do something
}

扩展方法的参数类型有限制吗?

最佳答案

简短的回答是,扩展方法只是一个公共(public)静态方法,可以像第一个参数的实例方法一样访问(感谢 this 关键字)。这意味着您可以使用与在任何静态方法中相同的参数。

但是如果您希望参数实际上是通用的,您需要将方法更改为:

public static IEnumerable<TElement> GetSequenceDescendants<TElement, TName>(this IEnumerable<TElement> elements, List<TName> names)
{
//do something
}

您必须在方法定义中指定所有通用参数。

此外,您不能使用 params除了数组以外的任何关键字,即 params TName[]没关系,但是params List<TName>不是。

关于c# - 扩展方法可以有泛型参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4787551/

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