C#:扩展中的多个类型参数 [英] C#: Multiple type parameters in extensions

查看:87
本文介绍了C#:扩展中的多个类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个可以切片任何类似数组的类的扩展(因为切片在标准库中很奇怪)。例如:

I was trying to create an extension that could slice any array-like class (since slicing is oddly absent in the standard libraries). For example:

public static M Slice<M,T>(this M source, int start, int end) where M : IList<T>
{
    //slice code
}

然而,编译时不会将此方法附加到M类型的对象(即使它的错误消息声称它正在寻找它)。它似乎相当依赖于方法本身的类型参数,例如,以某种方式,但我不完全理解事情是如何工作的。

However, the compiled does not attach this method to objects of type M (even though its error message claims that that is what it is looking for). It seems rather to be dependent upon the type parameters of the method itself, e.g. in some manner, but I don't fully understand how things are working.

(是的,人们可以很容易地编写一个仅适用于List的示例,但我是好奇,如果这是可能的。)

(yes, one could easily write an example that just works with List, but I'm curious if this is even possible.)

推荐答案

有编译器不会推断类型 T 自动处理这些情况。即使它不是扩展方法,您仍需手动指定类型参数。

There compiler does not infer the type T automatically for these cases. Even if it wasn't an extension method, you still had to specify the type parameters manually.

例如,如果类声明为:

class MyNastyClass : IList<int>, IList<double> {
}

您期望什么 T 是? int double ?因此,您必须使用特定参数手动调用它:

What would you expect T to be? int or double? As a result, you'll always have to manually call it with the specific parameters:

Slice(myList, 0, 10); // compile-time error, T cannot be inferred.
Slice<IList<int>, int>(myList, 0, 10); // works.

解决方法是删除类型参数 T (此处不需要约束):

The workaround is to remove the type parameter T (no constraints needed here):

public static void Slice<M>(this IList<M> source, int start, int end)

顺便提一句,请注意,这绝不涉及参数的数量。只要编译器能够推断它们(根据C#规范的泛型类型推断规则),就可以拥有任意数量的类型参数。例如,可以在不指定类型参数的情况下调用此扩展方法:

By the way, note that, this is by no means related to the number of parameters. You can have as many type parameters as you like, as long as the compiler can infer them (according to C# specification generic type inference rules). For example, this extension method can be called without specifying type arguments:

public static void SomeMethod<T,U>(this IEnumerable<T> collection, U anotherParameter)

这篇关于C#:扩展中的多个类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆