开发者

Defining an extension method on IEnumerable<T> where T is specific kind of type?

I want a method to only work on types which implement the /, +, -, * operators. Is there any "clean" way to do t开发者_如何转开发his?


This would require an interface, such as IArithmetic.

Unfortunately, this doens't work currently. This is a highly requested feature, however.

There are some workarounds, usually requiring working with a second generic parameter, but most wouldn't work with IEnumerator<T>.


You can define constraints on Type Parameters. So you can require T to implement an interface:

public static class Classy
{
    public static void Extension<T>(this IEnumerable<T> Ninjas) 
        where T : IMathStuff
    {

    }
}

This requires all T to implement IMathStuff. Now, if you can't fit the operators into the interface IMathStuff, you can leave the interface blank as a Marker Interface and only apply it to classes that do implement the operators.

This kind of assumes you're working with all custom classes and not the built-in types. It's a workaround for something that isn't exactly supported.


There is not a clean way to do this. You will need to implement IEnumberable<int>, IEnumberable<float>... etc


Not at compile-time. You'd have to use reflection, I think.

A lot of those are value types such as int and long, "where T : struct" but there is no interface or base type that is common to them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜