简体   繁体   English

泛型和扩展方法一起

[英]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. 我希望它也接受例如ushort和uint。 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). 根据您的评论,您可以执行以下操作来有效地限制T的类型(添加保护语句)。

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. 注意:正如马丁·哈里斯(Martin Harris)在评论中指出的那样,您实际上不需要在这里使用泛型。 The Array type from which all arrays derive will suffice. 从中派生所有数组的Array类型就足够了。

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 @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 但是,用作约束的类型必须是接口,非密封类或类型参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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