如何在不创建新列表的情况下转换列表(需要引用原始列表)

时间:2015-07-10 04:35:33

标签: c# list casting

我正在尝试创建一个将编辑对象列表的类。它的构造函数接受任何实现' INameable'接口。然后,它的方法可以再添加一个成员到列表中。

例如:

public static class Data
{
    //All of these object types implement the INameable interface
    List<Apple> Apples = new List<Apple>();
    List<Orange> Oranges = new List<Orange>();
    List<Pear> Pears = new List<Pear>();
}

public class ListEditor
{
    private List<INameable> _list;
    private Type _type;
    public  ListEditor(List<INameable> l, Type t)
    {
        _list = l;
        _type = t
    }

    public void AddMember()
    {
        var newObject Activator.CreateInstance(_type);
        _list.Add((iNameable)newObject );
    }
}

Program
{
    //these lines are not working because the casting is invalid...
    private ListEditor _appleEditor = new ListEditor((List<INameable>)Data.Apples, TypeOf(Apple));
    private ListEditor _orangeEditor = new ListEditor((List<INameable>)Data.Oranges, TypeOf(Orange));
    private ListEditor _pearEditor = new ListEditor((List<INameable>)Data.Pears, TypeOf(Pear));
}

问题:

将List列为List而不创建新列表的正确语法是什么(这将破坏对原始列表的引用)

1 个答案:

答案 0 :(得分:1)

听起来你可以扩展List<T>并向你的班级添加你需要的新方法:

public class ListEditor<T> : List<T> where T : new()
{
    public void AddMember()
    {
        Add(new T());
    }
}

像这样使用:

var _appleEditor = new ListEditor<Apple>();

_appleEditor.AddMember();

var _orangeEditor = new ListEditor<Orange>();

_orangeEditor.AddMember();

或者,如果您真的只想要一个可以保存对原始列表的引用的类,并且有一个方法可以向其添加新项目:

public class ListEditor<T> where T : new()
{
    private readonly List<T> originalList;

    public ListEditor(List<T> list)
    {
        originalList = list;
    }

    public void AddMember()
    {
        originalList.Add(new T());
    }
}

var originalApples = new List<Apple>();

var newApples = new ListEditor<Apple>(originalApples);
newApples.AddMember();