c# - 将对象类型转换为 C# 类

标签 c#

问题:我正在尝试将对象类型转换回根类
我从一个通用双向链表开始,我可以添加值但不能检索它们

class CarPart
{
    public long PartNumber;
    public string PartName;
    public double UnitPrice;
}

class DoublyLinkedList
{
    private class DoublyLinkedListNode
    {
        private object element;
        private DoublyLinkedListNode next;
        private DoublyLinkedListNode previous;

        public DoublyLinkedListNode(object element)
        {
            this.element = element;
            this.next = null;
            this.previous = null;
        }

        public DoublyLinkedListNode(object element, DoublyLinkedListNode prevNode)
        {
            this.element = element;
            this.previous = prevNode;
            prevNode.next = this;
        }

        public object Element
        {
            get { return this.element; }
            set { this.element = value; }
        }

        public DoublyLinkedListNode Next
        {
            get { return this.next; }
            set { this.next = value; }
        }

        public DoublyLinkedListNode Previous
        {
            get { return this.previous; }
            set { this.previous = value; }
        }
    }

    private DoublyLinkedListNode head;
    private DoublyLinkedListNode tail;
    private int count;

    public DoublyLinkedList()
    {
        this.head = null;
        this.tail = null;
        this.count = 0;
    }

    public int Count
    {
        get { return this.count; }
    }

    public object this[int index]
    {
        get
        {
            if (index >= count || index < 0)
            {
                throw new ArgumentOutOfRangeException("Out of range!");
            }
            DoublyLinkedListNode currentNode = this.head;
            for (int i = 0; i < index; i++)
            {
                currentNode = currentNode.Next;
            }
            return currentNode.Element;
        }
        set
        {
            if (index >= count || index < 0)
            {
                throw new ArgumentOutOfRangeException("Out of range!");
            }
            DoublyLinkedListNode currentNode = this.head;
            for (int i = 0; i < index; i++)
            {
                currentNode = currentNode.Next;
            }
            currentNode.Element = value;
        }
    }
    public void Add(object item)
    {
        if (this.head == null)
        {
            this.head = new DoublyLinkedListNode(item);
            this.tail = this.head;
        }
        else
        {
            DoublyLinkedListNode newItem = new DoublyLinkedListNode(item, tail);
            this.tail = newItem;
        }
        count++;
    }

    public void Insert(object item, int index)
    {
        count++;
        if (index >= count || index < 0)
        {
            throw new ArgumentOutOfRangeException("Out of range!");
        }
        DoublyLinkedListNode newItem = new DoublyLinkedListNode(item);
        int currentIndex = 0;
        DoublyLinkedListNode currentItem = this.head;
        DoublyLinkedListNode prevItem = null;
        while (currentIndex < index)
        {
            prevItem = currentItem;
            currentItem = currentItem.Next;
            currentIndex++;
        }
        if (index == 0)
        {
            newItem.Previous = this.head.Previous;
            newItem.Next = this.head;
            this.head.Previous = newItem;
            this.head = newItem;
        }
        else if (index == count - 1)
        {
            newItem.Previous = this.tail;
            this.tail.Next = newItem;
            newItem = this.tail;
        }
        else
        {
            newItem.Next = prevItem.Next;
            prevItem.Next = newItem;
            newItem.Previous = currentItem.Previous;
            currentItem.Previous = newItem;
        }
    }
    public void Remove(object item)
    {
        int currentIndex = 0;
        DoublyLinkedListNode currentItem = this.head;
        DoublyLinkedListNode prevItem = null;
        while (currentItem != null)
        {
            if ((currentItem.Element != null &&
                currentItem.Element.Equals(item)) ||
                (currentItem.Element == null) && (item == null))
            {
                break;
            }
            prevItem = currentItem;
            currentItem = currentItem.Next;
            currentIndex++;
        }
        if (currentItem != null)
        {
            count--;
            if (count == 0)
            {
                this.head = null;
            }
            else if (prevItem == null)
            {
                this.head = currentItem.Next;
                this.head.Previous = null;
            }
            else if (currentItem == tail)
            {
                currentItem.Previous.Next = null;
                this.tail = currentItem.Previous;
            }
            else
            {
                currentItem.Previous.Next = currentItem.Next;
                currentItem.Next.Previous = currentItem.Previous;
            }
        }
    }
    public void RemoveAt(int index)
    {
        if (index >= this.count || index < 0)
        {
            throw new ArgumentOutOfRangeException("Out of range!");
        }

        int currentIndex = 0;
        DoublyLinkedListNode currentItem = this.head;
        DoublyLinkedListNode prevItem = null;
        while (currentIndex < index)
        {
            prevItem = currentItem;
            currentItem = currentItem.Next;
            currentIndex++;
        }
        if (this.count == 0)
        {
            this.head = null;
        }
        else if (prevItem == null)
        {
            this.head = currentItem.Next;
            this.head.Previous = null;
        }
        else if (index == count - 1)
        {
            prevItem.Next = currentItem.Next;
            tail = prevItem;
            currentItem = null;
        }
        else
        {
            prevItem.Next = currentItem.Next;
            currentItem.Next.Previous = prevItem;
        }
        count--;
    }
    public int indexOf(object item)
    {
        int index = 0;
        DoublyLinkedListNode currentItem = this.head;
        while (currentItem != null)
        {
            if (((currentItem.Element != null) && (item == currentItem.Element)) ||
                ((currentItem.Element == null) && (item == null)))
            {
                return index;
            }
            index++;
            currentItem = currentItem.Next;
        }
        return -1;
    }
    public bool Contains(object element)
    {
        int index = indexOf(element);
        bool contains = (index != -1);
        return contains;
    }

    public void Clear()
    {
        this.head = null;
        this.tail = null;
        this.count = 0;
    }

    public object First()
    {
        if (this.count < 0)
        {
            throw new ArgumentOutOfRangeException("Out of range!");
        }
        else
            return this.head.Element;
    }

    public object Retrieve(int Position)
    {
        DoublyLinkedListNode current = this.head;

        for (int i = 0; i < Position && current != null; i++)
            current = current.Next;
        return current;
    }
}

class Program
{
    static void Main(string[] args)
    {

        DoublyLinkedList Parts = new DoublyLinkedList();
        object element;
        CarPart Part;
        CarPart PartToFind;

        Part = new CarPart();
        Part.PartNumber = 9743;
        Part.PartName = "Air Filter";
        Part.UnitPrice = 8.75;
        Parts.Add(Part);

        Part = new CarPart();
        Part.PartNumber = 27487;
        Part.PartName = "Clutch Disk";
        Part.UnitPrice = 47.15;
        Parts.Add(Part);

        Part = new CarPart();
        Part.PartNumber = 87873;
        Part.PartName = "Brake Disk";
        Part.UnitPrice = 35.15;
        Parts.Add(Part);

        Part = new CarPart();
        Part.PartNumber = 27644;
        Part.PartName = "A/C Filter Drier";
        Part.UnitPrice = 55.55;
        Parts.Add(Part);

        Console.WriteLine(" -=- Store Inventory -=-");
        Console.WriteLine("Number of Parts: {0}", Parts.Count);

        object item = (object)Parts;

        for (int i = 0; i < Parts.Count; i++)
        {
            // CarPart part = (CarPart)Parts.Retrieve(i);
            element = Parts.Retrieve(i);

            if (element != null)
            {
                // FAILS HERE AFTER RETRIEVING THE ELEMENT
                CarPart part = (CarPart)element;

                Console.WriteLine("\nCar Part Information");
                Console.WriteLine("Part #:      {0}", part.PartNumber);
                Console.WriteLine("Description: {0}", part.PartName);
                Console.WriteLine("Unit Price:  {0:C}", part.UnitPrice);
            }
        }
    }
}

我想要实现的是使用双向链表来存储许多不同的类型——将项目添加到链表没有问题,但我尝试了很多不同的类型转换方式,但都失败了。

感谢您就应该解决的简单问题提出任何建议。

最佳答案

你的 Retrieve方法返回节点本身——而不是节点内的值,我认为这是您所期望的。这就是为什么你得到一个 InvalidCastException .您只需要更改 Retrieve 的最后一行来自

return current;

return current.element;

我还强烈建议您制作 DoublyLinkedList一个通用类型(即 DoublyLinkedList<T> ),此时您不需要强制转换,并且错误在编译时会很明显。

关于c# - 将对象类型转换为 C# 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25825918/

相关文章:

c# - 在 Canvas 上选择已绑定(bind)的路径

c# - 处理一个集合,然后处理它的内容

c# - 不带\0027 将字符串序列化为 JSON

c# - 向字符串数组添加新项目

c# - 单元测试保存更改失败

c# - Windows Phone ScheduleAgent 在设定的时间段抓取图像

c# - 格式化 ESRI 地理编码器的 RestSharp 请求

c# - 如何搜索除id之外的其他字段

c# - 适用于 Windows 和 Linux 的同一台机器上的套接字

c# - 有什么方法可以检查代码更改是否更改了二进制文件?