2012-04-18 44 views
1

我已經設法創建我自己的IList子類使用我在MSDN上的另一個線程上找到的一些代碼。我已經添加了一些我自己的方法,並在基本場景中測試了這個類,並且它似乎工作正常。我怎樣才能轉換爲子類型IList <T>從列表<T>

問題是,當我嘗試和使用常規.ToList()方法我返回一個List而不是我的自定義pList。顯然我需要將它投射到我的新類型,但我不確定如何。我是否需要在我的自定義iList中實現另一種方法,以便爲它分配不同的格式?

我的課堂聲明如下所示。

public class pList<T> : IList<T> 

詹姆斯

回答

4

你將不能夠直接施放到List<T>pList<T>。你可以做一個擴展方法(就像ToList)。假設你的類有一個構造函數的IEnumerable<T>填充列表:

static class EnumerableExtensions 
{ 
    static pList<T> ToPList<T>(this IEnumerable<T> sequence) { return new pList<T>(sequence); } 
} 

如果你的類沒有這樣的構造函數,你可以添加一個,或做這樣的事情:

static class EnumerableExtensions 
{ 
    static pList<T> ToPList<T>(this IEnumerable<T> sequence) 
    { 
     var result = new pList<T>(); 
     foreach (var item in sequence) 
      result.Add(item); 
     return result; 
    } 
} 

我的pList類確實有一個構造函數需要IEnumerable添加了您的擴展方法,但我仍然無法在列表中看到ToPList()我錯過了什麼?

首先,如果你有這樣的構造函數,你需要將現有List<T>轉換爲pList<T>,你當然可以這樣做:

List<T> originalList = GetTheListSomehow(); 
var newList = new pList<T>(originalList); 

要使用的擴展方法,你必須確保該方法在範圍內。我沒有爲我的示例添加訪問修飾符。把internalpublic酌情:

public static class EnumerableExtensions 
{ 
    internal static pList<T> ToPList<T> //... 

另外,如果你想使用擴展方法在不同的命名空間,你必須在範圍using指令。例如:

namespace A { public static class EnumerableExtensions { ... 

在別處:

using A; 
// here you can use the extension method 

namespace B 
{ 
    public class C 
    { 
     ... 

namespace B 
{ 
    using A; 
    // here you can use the extension method 

    public class C 
    { 
     ... 
+0

你好,我的plist類確實有一個構造函數的IEnumerable 添加您的擴展方法,但我仍然無法看到ToPList()內的列表我錯過了什麼嗎? – 2012-04-18 19:11:39

+0

@JarmezDeLaRocha你在「列表'」內是什麼意思?「?你的意思是在intellisense中嗎? – phoog 2012-04-18 19:14:54

+0

是的,當我列出。我沒有看到例如像我看到tolist或toarray的榜單。我錯過了這個觀點嗎?我只是在閱讀這些擴展方法,現在他們對我來說是新的! – 2012-04-18 19:17:48

1

IList<T>是一個接口。不是班級。如果你正在處理你的類作爲IList<T>一個實例,你可以簡單地投退,而不是調用ToList()

2

你也可以定義一個implicit演員。

public static implicit operator pList<T>(List<T> other) 
{ 
    //Code returning a pList 
} 
4

我不太確定你打算怎樣來完成,但也許你可以添加以下代碼:使用擴展方法

// Constructor which handles enumerations of items 
public pList(IEnumerable<T> items) 
{ 
    // this.innerCollection = new Something(items); 
} 

然後:

public static class pListExtensions 
{ 
    public static pList<T> ToPList<T>(this IEnumerable<T> items) 
    { 
     return new pList<T>(items); 
    } 
} 

稍後在您的代碼中使用:

var items = (from t in db.Table 
      where condition(t) 
      select new { Foo = bar(t), Frob = t.ToString() }).ToPList(); 
2

你需要創建一個返回新的列表類型的擴展方法

public static List<TSource> ToMyList<TSource>(this IEnumerable<TSource> source) 
{ 
    if (source == null) 
    { 
     throw ArgumentNullException("source"); 
    } 
    return new pList<TSource>(source); 
} 
相關問題