简体   繁体   中英

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 static 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);
    }
}

使用普通(非扩展)方法中的泛型的相同方法:使用泛型语法中引入的占位符类型名称:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM