简体   繁体   English

C#和基类派生转换

[英]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! 以下代码位于http://ideone.com/CaXQS上 ,如果有帮助的话...谢谢!

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. 在您的ConvertAll代码中,您只是强制转换。 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? 例如,您希望将object强制转换为FileStream做什么? Which file would it refer to? 它指的是哪个文件?

If you want to create a new object in the ConvertAll projection, just do that: 如果要在ConvertAll投影中创建一个对象,只需执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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