c# - 如何从 List<T> 转换为 IList<T> 的子类型

标签 c# .net list

我已经设法使用我在 MSDN 的另一个线程上找到的一些代码创建了我自己的 IList 子类。我添加了一些自己的方法,并在基本场景中测试了该类,它似乎工作正常。

问题是,当我尝试使用常规 .ToList() 方法时,返回的是一个 List 而不是我的自定义 pList。显然我需要将它转换为我的新类型,但我不确定如何。我是否需要在我的自定义 iList 中实现另一种方法以允许它以不同的格式分配?

我的类声明如下所示。

public class pList<T> : IList<T>

詹姆斯

最佳答案

你将无法施放 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;
    }
}

my pList class does have a constructor that takes IEnumerable have added your extension method but i am still unable to see ToPList() within the List Am i missing something?

首先,如果你有这样一个构造函数,并且你想转换一个现有的 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
    {
        ...

关于c# - 如何从 List<T> 转换为 IList<T> 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215637/

相关文章:

.net - 在 C# dll 中缓存数据的最佳方法是什么?

c# - LINQ to entities 无法识别方法 'System.DecimalToDecimal

c# - 报告查看器 - 在同一页上换行表

c# - 在 ASP.NET MVC View 中转储对象 - 对象转储器 View

.net - 使用 jQuery 将 JSON 对象发送到 asp.net WebMethod 时出错

c - 为什么我在这个列表中得到垃圾值

c# - 条件拆分列表或数组(或获取子列表等)

python - 如何确定 pandas 数据框列中列表的长度

c# - 等待数千个任务

c# - Linq 中不区分大小写的 "contains"