无法在 C# 和 XNA 中正确初始化父类的子类



我在寻找解决问题的方法时发现了这个网站,我想知道是否有人可以帮助我尝试解决我的困境。

我使用XNA和c#来创建一些用户能够从他们随机选择的零件组装汽车的东西。汽车不需要有四个轮子和一个挡风玻璃。它只需要由用户选择的至少7个部分组成。我创建了一个名为"Car"的类,它将创建用户选择的所有7个部件实例。这些部件属于"CarPart"类。我还创建了"CarPart"的两个独立子类"Wheel"one_answers"挡风玻璃"。我打算以后对这些部分进行扩展,例如添加"门"one_answers"后备箱"等。

所以我所做的是在我的Car类中,我声明了7个类型为"CarPart"的对象,然后将它们声明为new Windshield()。或new Wheel().

但是当我尝试访问挡风玻璃或车轮类的初始化函数时,它只允许我访问父类"CarPart"的初始化函数。

我是在尝试用正确的方式做这件事,还是应该找到另一种解决问题的方法?

我也试过使用Virtual和Override来尝试重载函数,但我似乎也不能正常工作,它只是说,"找不到合适的方法来重载"。

我已经包含了这些类的代码。

任何帮助都将是惊人的,我已经卡住了好几天,我不能继续我的项目,如果没有这个功能,用户能够按照他们的意愿组装汽车。

我在这个链接上发现了类似的东西,但我似乎无法让它工作。http://csharp-station.com/Tutorial/CSharp/Lesson09

我肯定我在做一些我看不到的蠢事,因为我盯着同一个问题太久了。

汽车类:

namespace TestGame4
{
    class Car
    {
        //Car consists of 7 CarParts chosen by the user//
        //e.g.: 
        CarPart Part1, Part2, Part3, Part4, Part5, Part6, Part7; 
        public void Initialize(CarPart part1, CarPart part2, CarPart part3, CarPart part4, CarPart part5, CarPart part6, CarPart part7)
        {
            Part1 = part1;
            Part2 = part2;
            Part3 = part3;
            Part4 = part4;
            Part5 = part5;
            Part6 = part6;
            Part7 = part7;       
            ***//This is the part that doesn't work how I want it to. I want it to initialize 
            //as a Windshield class, but it's only initializing as a CarPart class//***
            part1.Initialize(
        }
    }
}
CarPart class:
namespace TestGame4
{
    public class CarPart
    {
        public void Initialize(string assetName, Vector2 Position)
        {
        }
    }
}

挡风玻璃类:

namespace TestGame4
{
    public class Windshield : CarPart
    {
        public void Initialize(Vector2 Position)
        {
        }
    }
}

轮类:

namespace TestGame4
{
    public class Wheel : CarPart
    {
        public void Initialize(Vector2 Position)
        {
        }
    }
}

我的主要Game1类,我在其中初始化Car类,并尝试设置它与挡风玻璃和车轮类作为参数:

namespace TestGame4
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Car myCar;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            myCar = new Car();
            myCar.Initialize(new Windshield(), new Wheel(), new Windshield(), new Wheel(), new Windshield(), new Wheel(), new Windshield());           
            base.Initialize();
        }
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            // TODO: use this.Content to load your game content here
        }
        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            // TODO: Add your update logic here
            base.Update(gameTime);
        }
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            // TODO: Add your drawing code here
            base.Draw(gameTime);
        }
    }
}
我将非常感激我得到的任何帮助!提前感谢!

您的WindshieldWheel都是CarPart的后代。对于Car类,它们只是CarPart(按定义),因此Car不知道它们是Wheel还是Windshield。至少在编译时不会。

要解决这个问题,需要为这些类添加一个接口。或者在CarPart中添加一个抽象函数,这更容易。

abstract class CarPart
{
   public abstract void Initialize(Vector2 position);
   public void Initialize(string assetName, Vector2 position)
   {
   }
}

之后,两个子类都需要重写这个函数,否则它们也将是抽象的(抽象类不能用来创建对象)。

接口非常简单:接口是你从类中需要的行为。例如

interface IInitializable
{
   void Initialize (Vector2 position);
}
class WindShield: IIinitializable
{
   void Initialize (Vector2 position)
   {
      ...
   }
}

那么你可以写在CarPart:

IInitializable [] parts = new IInitializable [7];
parts[0] = new WindShield();
...
parts[6] = new Wheel();
parts[3].Initialize(new Vector2(0, 0));

所以这些部分都符合接口IInitializable,你可以调用通用方法Initialize (Vector2)。当不同的不相关的类实现相同的行为时,接口是最有用的,比如IQueryableIDisposable等等。

最新更新