我正在尝试根据派生设置类自动实例化正确的派生类。
在这里,我有一个主基类和一个基本设置类
public abstract class BaseClass
{
public BaseClass() { }
public abstract BaseClassSettings Write();
}
public class BaseClassSettings
{
}
现在这是我的派生类及其设置类
public class DerivedFoo : BaseClass
{
public DerivedFoo(DerivedFooSettings settings)
{
// Apply settings
}
public override BaseClassSettings Write()
{
DerivedFooSettings settings = new DerivedFooSettings();
return settings;
}
}
public class DerivedFooSettings : BaseClassSettings
{
}
public class DerivedBar : BaseClass
{
public DerivedBar(DerivedBarSettings settings)
{
// Apply settings
}
public override BaseClassSettings Write()
{
DerivedBarSettings settings = new DerivedBarSettings();
return settings;
}
}
public class DerivedBarSettings : BaseClassSettings
{
}
我可以将所有派生类设置保存在一个数组中
DerivedFoo foo = new DerivedFoo();
DerivedBar bar = new DerivedBar();
BaseClassSettings[] s = new BaseClassSettings[2];
s[0] = foo.Write();
s[1] = bar.Write();
它以 XML 格式序列化到光盘。
如何根据派生设置类自动实例化派生类?
因此,如果数组元素是 DerivedBarSettings 类,则创建 DerivedBar 类的新实例。
我想在不使用越来越多的 else if 语句的情况下做到这一点,具体取决于类的数量。
if (BaseClassSettings is DerivedFooSettings)
new DerivedFoo(settings)
else if (BaseClassSettings is DerivedBarSettings)
new DerivedBar(settings)
如何才能做到这一点?
==================================================== ==============================
[编辑]
这是我正在使用的:
[
XmlInclude(typeof(DerivedSettingsClassA)),
XmlInclude(typeof(DerivedSettingsClassB)),
XmlInclude(typeof(DerivedSettingsClassC)),
XmlInclude(typeof(DerivedSettingsClassD)),
XmlInclude(typeof(DerivedSettingsClassE)),
]
public abstract class BaseSettingsClass
{
public abstract DerivedClass Load(Game1 game, OutputDimensionSettings settings);
}
唯一的缺点是我必须为所有派生类明确定义 XmlInclude。