將單個項目做爲IEnumerable傳遞

是否存在將T類型的單個項目傳遞給須要IEnumerable<T>參數的方法的通用方法? 語言是C#,框架版本2.0。 數組

當前,我正在使用一個輔助方法(它是.Net 2.0,因此我有一堆相似於LINQ的強制轉換/投影輔助方法),但這彷佛很愚蠢: app

public static class IEnumerableExt
{
    // usage: IEnumerableExt.FromSingleItem(someObject);
    public static IEnumerable<T> FromSingleItem<T>(T item)
    {
        yield return item; 
    }
}

固然,其餘方法是建立並填充List<T>Array並傳遞它,而不是IEnumerable<T>框架

[編輯]做爲擴展方法,它能夠命名爲: this

public static class IEnumerableExt
{
    // usage: someObject.SingleItemAsEnumerable();
    public static IEnumerable<T> SingleItemAsEnumerable<T>(this T item)
    {
        yield return item; 
    }
}

我在這裏想念什麼嗎? spa

[Edit2]咱們發現someObject.Yield() (如@Peter在下面的註釋中建議的)是此擴展方法的最佳名稱,主要是爲了簡潔起見,所以,若是有人想抓住它,它與XML註釋一塊兒使用: code

public static class IEnumerableExt
{
    /// <summary>
    /// Wraps this object instance into an IEnumerable&lt;T&gt;
    /// consisting of a single item.
    /// </summary>
    /// <typeparam name="T"> Type of the object. </typeparam>
    /// <param name="item"> The instance that will be wrapped. </param>
    /// <returns> An IEnumerable&lt;T&gt; consisting of a single item. </returns>
    public static IEnumerable<T> Yield<T>(this T item)
    {
        yield return item;
    }
}

#1樓

好吧,若是該方法指望一個IEnumerable ,則即便它僅包含一個元素,您也必須傳遞做爲列表的內容。 it

經過 io

new T[] { item }

由於我認爲論點應該足夠 class


#2樓

我想說的最簡單的方法是new T[]{item}; ; 沒有語法能夠作到這一點。 我能想到的最接近的等效項是params關鍵字,可是固然,這要求您有權訪問方法定義,而且只能與數組一塊兒使用。 擴展


#3樓

IMO是您的助手方法,是最乾淨的方法。 若是傳遞列表或數組,那麼不道德的代碼段可能會強制轉換它並更改內容,從而在某些狀況下致使異常行爲。 您可使用只讀集合,但這可能涉及更多包裝。 我認爲您的解決方案很是簡潔。


#4樓

在C#3(我知道您說過2)中,您能夠編寫一個通用擴展方法,該方法可能會使語法更容易接受:

static class IEnumerableExtensions
{
    public static IEnumerable<T> ToEnumerable<T>(this T item)
    {
        yield return item;
    }
}

而後,客戶端代碼爲item.ToEnumerable()


#5樓

我很驚訝沒有人建議使用類型T的參數來簡化客戶端API的方法的新重載。

public void DoSomething<T>(IEnumerable<T> list)
{
    // Do Something
}

public void DoSomething<T>(T item)
{
    DoSomething(new T[] { item });
}

如今,您的客戶代碼能夠作到這一點:

MyItem item = new MyItem();
Obj.DoSomething(item);

或列出:

List<MyItem> itemList = new List<MyItem>();
Obj.DoSomething(itemList);
相關文章
相關標籤/搜索