我正在创建一个生态系统模拟器,其中物种可用于模拟各种疾病,我的问题是我开始使用4种,但如果我需要更多......我需要更多变量来存储,我的问题是,是有没有办法通过Reflection让我在程序中执行事件时创建动态变量?谢谢!我正在使用Windows Presentation Foundation和C#
答案 0 :(得分:3)
处理这种情况的正常方法是为您的疾病种类建立一个基类,然后使用一个集合来保存它们:
public abstract class DiseaseBase
{
public abstract void Spread();
}
public class Anthrax : DiseaseBase
{
public override void Spread()
{
GetPostedToPolitician();
}
}
public class BirdFlu : DiseaseBase
{
public override void Spread()
{
Cluck();
SneezeOnHuman();
}
}
public class SwineFlu : DiseaseBase
{
public override void Spread()
{
//roll in mud around other piggies
}
}
public class ManFlu : DiseaseBase
{
public override void Spread()
{
//this is not contagious
//lie in bed and complain
//get girlfriend to make chicken soup
//serve chicken soup with beer and baseball/football/[A-Za-z0-9]+Ball
}
}
public List<DiseaseBase> DiseaseCollection = new List<Disease>();
因此,所有内容都作为基类(DiseaseBase)存储在集合中,并且通过在基础和/或接口中适当使用抽象方法,您始终可以将每个疾病实例作为基础对象进行处理。