我已经设法使用我在 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);
要使用扩展方法,您必须确保该方法在范围内。我没有在示例中添加访问修饰符。放internal
或 public
在适当的时候:
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/