簡體   English   中英

方法重載和泛型參數

[英]Method overload and generic parameter

我讀了這個問題 ,我正在嘗試做類似的事情:

static class ExtentionMethods
{
    static public void MyReset<T>(this T col)
    {
        Console.WriteLine("Not a collection!");
    }

    static public void MyReset<T, U>(this T col) where T : ICollection<U>
    {
        col.Clear();
        Console.WriteLine("Cleared!");
    }

    // and maybe more overload for T : IWhatevetInterface<U>
}

所以List<T>和實現ICollection<T>會選擇第二種方法,而MyClass (MyClass只是一些沒有實現ICollection的類)會選擇第一種方法,例如:

List<int> list1 = new List<int>();
list1.MyReset<List<int>, int>(); // "Cleared!"
MyClass x = new MyClass(); 
x.MyReset(); // "Not a collection!"

它工作正常,但問題是,我怎么能避免寫<List<int>, int>用於list1.MyReset<List<int>, int>() 我想簡單地編寫list1.MyReset()

目標是保持區分ICollection<T>和其他類的能力,但也不是明確提供通用參數。

回應評論:我打算添加更多重載,所以不僅僅是Yes-CollectionNot-Collection

C#在其類型推理算法中不使用泛型約束。

但是,它看起來並不像您實際需要類型約束。 您可以像這樣簡化代碼,這確實有效:

static public void MyReset(this object col)
{
    Console.WriteLine("Not a collection!");
}

static public void MyReset<T>(this ICollection<T> col)
{
    col.Clear();
    Console.WriteLine("Cleared!");
}

static public void MyReset<T>(this IWhateverYouLike<T> col)
{
    col.ClearItIfYouLike();
    Console.WriteLine("Cleared!");
}

暫無
暫無

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

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