简体   繁体   中英

C# and Base-to-Derived Class Casting

I want to project info from a list of base-class instances into a list of derived-class instances, but I keep running into casting exceptions. Here's an example of what I'm trying to do... how do I make it work?

The following code is up at http://ideone.com/CaXQS , if that helps... thanks in advance!

using System;
using System.Collections.Generic;

namespace AddingReversedNumbers
{
        public class MyDerivedClass : MyBaseClass, IMyInterface
        {
                public int InterfaceProperty { get; set; }
                public int DerivedClassProperty { get; set; }
                public List<int> DerivedClassList { get; set; }
        }

        public class MyBaseClass
        {
                public int BaseClassProperty { get; set; }
        }

        public interface IMyInterface
        {
                int InterfaceProperty { get; set; }
        }

        class Program
        {
                static void Main()
                {
                        //// This code works just fine.
                        //var derivedList = new List<MyDerivedClass>();
                        //derivedList.Add(new MyDerivedClass { BaseClassProperty = 10, DerivedClassProperty = 20, InterfaceProperty = 30 });
                        //derivedList.Add(new MyDerivedClass { BaseClassProperty = 20, DerivedClassProperty = 40, InterfaceProperty = 60 });
                        //var baseList = derivedList.ConvertAll(x => (MyBaseClass)x);

                        // This code breaks when ConvertAll() is called.
                        var baseList = new List<MyBaseClass>();
                        baseList.Add(new MyBaseClass{ BaseClassProperty = 10 });
                        baseList.Add(new MyBaseClass{ BaseClassProperty = 20 });
                        var derivedList = baseList.ConvertAll(x => (MyDerivedClass)x);
                }
        }
}

In your ConvertAll code you're just casting. You can't cast a base class instance to a derived class instance. For example, what would you expect casting object to FileStream to do? Which file would it refer to?

If you want to create a new object in the ConvertAll projection, just do that:

var derivedList = baseList.ConvertAll
      (x => new MyDerivedClass { BaseClassProperty = x.BaseClassProperty });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM