簡體   English   中英

泛型和擴展方法一起

[英]Generics and Extension Methods Together

我需要為數組類創建一個擴展方法,但是此擴展方法必須能夠接受許多數據類型,因此它也必須是通用的。

在下面的代碼中,擴展方法僅接受字節數據類型。 我希望它也接受例如ushort和uint。 我認為最好的方法是在此處創建泛型。 但是我該如何使用數組呢?

謝謝!!!

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

擴展方法中的泛型實際上並沒有什么特別的,它們的行為與普通方法中的行為相同。

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

根據您的評論,您可以執行以下操作來有效地限制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);
}

注意:正如馬丁·哈里斯(Martin Harris)在評論中指出的那樣,您實際上不需要在這里使用泛型。 從中派生所有數組的Array類型就足夠了。

如果您想要一個更優雅的解決方案,而要花更多的代碼,則可以創建該方法的重載:

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

您可以像這樣進行約束

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

但是,用作約束的類型必須是接口,非密封類或類型參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM