简体   繁体   English

在以基本情况为参数的函数中传递派生类

[英]Pass derived classes in a function with base case as parameter

I am writing a C# program that is a basic text rpg game. 我正在编写一个C#程序,它是一个基本的文本rpg游戏。 When I save the game, I want to pass the character into a save function that will then get the data from the character and write it into an xml file. 当我保存游戏时,我想将角色传递到保存函数,该函数将随后从角色中获取数据并将其写入xml文件。 I have one base class Character and three derived classes: Knight , Rogue , and Wizard . 我有一个基类Character和三个派生类: KnightRogueWizard They each have a special int that I want to write to an xml file. 它们每个都有一个特殊的int,我想将其写入xml文件。

private void Save(Character c, string file) {
    //Sample part of writing the data
    XmlNode nodeName = playerData.CreateElement("name");
    nodeName.AppendChild(playerData.CreateTextNode(c.name));
    nodeDetails.AppendChild(nodeName);
}

I want to pass in a Knight , Rogue , or Wizard into this function and be able to get any variables in the derived classes that are not in the base class. 我想将KnightRogueWizard传递给此函数,并能够获取派生类中不在基类中的任何变量。 Is there a way to do this? 有没有办法做到这一点?

Yes, through the use of casting. 是的,通过使用铸造。

private void Save(Character c, string file)
{
    if(c is Knight)
    {
        k = (Knight)c;
        // Do whatever with k
    }
    else if (c is Rogue)
    {
        r = (Rogue)c;
        // Do whatever with k
    }
}

However, this undermines the polymorphic structure you have set up - the whole point of polymorphism is that you shouldn't have to do this. 但是,这破坏了您已建立的多态结构-多态的全部意义在于您不必这样做。

It would be better practice if the Character class had an abstract or virtual method that returned the data needed to save. 如果Character类具有返回要保存的数据的abstractvirtual方法,则将是更好的做法。 Each subclass would override this method to return the required information (including anything special for that subclass), so you would never need to check what type of Character was passed in. 每个子类都将重写此方法以返回所需的信息(包括该子类的所有特殊信息),因此您无需检查传入的Character类型。

See if this helps 看看是否有帮助

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Rogue rogue = new Rogue();
            Save(rogue, "1234");
        }
        static void Save(Character c, string file)
        {
            if(c.GetType() == typeof(Knight))
            {
            }
            if (c.GetType() == typeof(Rogue))
            {
            }
            if (c.GetType() == typeof(Wizard))
            {
            }


        }
    }

    public class Character
    {
    }
    public class Knight : Character
    {
    }
    public class Rogue : Character
    {
    }
    public class Wizard : Character
    {
    }
}

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

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