![](/img/trans.png)
[英]How to pass various derived classes of the same interface within a generic List as a parameter to the function?
[英]Pass derived classes in a function with base case as parameter
我正在編寫一個C#程序,它是一個基本的文本rpg游戲。 當我保存游戲時,我想將角色傳遞到保存函數,該函數將隨后從角色中獲取數據並將其寫入xml文件。 我有一個基類Character和三個派生類: Knight , Rogue和Wizard 。 它們每個都有一個特殊的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);
}
我想將Knight , Rogue或Wizard傳遞給此函數,並能夠獲取派生類中不在基類中的任何變量。 有沒有辦法做到這一點?
是的,通過使用鑄造。
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
}
}
但是,這破壞了您已建立的多態結構-多態的全部意義在於您不必這樣做。
如果Character
類具有返回要保存的數據的abstract
或virtual
方法,則將是更好的做法。 每個子類都將重寫此方法以返回所需的信息(包括該子類的所有特殊信息),因此您無需檢查傳入的Character
類型。
看看是否有幫助
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.