开发者

Generics and Extension Methods Together

I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic.

In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance. I believe that the best way to do that is creating a generic type here. But how can I do that using arrays?

Thanks!!!

public static class MyExtensions
{
    public stat开发者_JAVA百科ic int GetLastIndex(this byte[] buffer)
    {
        return buffer.GetUpperBound(0);
    }
}


Generics in extension methods aren't really anything special, they behave just like in normal methods.

public static int GetLastIndex<T>(this T[] buffer)
{
    return buffer.GetUpperBound(0);
}

As per your comment, you could do something like the following to effectively restrict the type of T (adding guard statements).

public static int GetLastIndex<T>(this T[] buffer) where T : struct
{
    if (!(buffer is byte[] || buffer is ushort[] || buffer is uint[]))
        throw new InvalidOperationException(
            "This method does not accept the given array type.");

    return buffer.GetUpperBound(0);
}

Note: As Martin Harris pointed out in a comment, you don't actually need to use generics here. The Array type from which all arrays derive will suffice.

If you want a more elegant solution, at the cost of slightly more code, you could just create overloads of the method:

public static int GetLastIndex(this byte[] buffer)
{
    return GetLastIndex(buffer);
}

public static int GetLastIndex(this ushort[] buffer)
{
    return GetLastIndex(buffer);
}

public static int GetLastIndex(this uint[] buffer)
{
    return GetLastIndex(buffer);
}

private static int GetLastIndex(Array buffer)
{
    return buffer.GetUpperBound(0);
}


public static class MyExtensions
{
    public static int GetLastIndex<T>(this T[] buffer)
    {
        return buffer.GetUpperBound(0);
    }
}


Same way you do generics in normal (non-extension) methods: Use a placeholder type name introduced in the generic syntax:

public static int GetLastIndex<TElement>(this TElement[] buffer)


@RHaguiuda

You can make constraint like

public static class MyExtensions{
public static int GetLastIndex<T>(this T[] buffer) where T: Integer
{
    return buffer.GetUpperBound(0);
}}

But, type used as a constraint must be an interface, a non-sealed class or a type parameter

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜