【发布时间】:2011-10-20 08:40:24
【问题描述】:
我正在编写一个允许用户运行测试的应用程序。测试由许多不同的对象组成,例如配置、温度和基准。设置之类的东西在xml之间来回保存。我在代码中传递了不同的 XElement,因此我可以针对不同的情况以不同的方式构建最终的 xml 文档。我想做这样的事情:
public abstract class BaseClass<T>
{
abstract static XElement Save(List<T>);
abstract static List<T> Load(XElement structure);
}
public class Configuration : BaseClass<Configuration>
{
public string Property1 { get; set; }
public string Property2 { get; set; }
//etc...
public static XElement Save(List<Configuration>)
{
XElement xRoot = new XElement("Root");
//etc...
return xRoot;
}
public static List<Configuration> Load(XElement structure)
{
List<BaseClass> list = new List<BaseClass>();
//etc...
return list;
}
}
public class Temperature : BaseClass<Temperature>
{
public float Value { get; set; }
public static XElement Save(List<Temperature>)
{
//save
}
public static List<Temperature> Load(XElement structure)
{
//load
}
}
[EDIT]:修改问题(更改上述函数的签名)[/EDIT]
当然,我实际上是不允许重写 BaseClass 的静态方法的。解决这个问题的最佳方法是什么?我希望以下内容尽可能有效:
List<Temperature> mTemps = Temperature.Load(element);
List<Configuration> mConfigs = Configuration.Load(element);
Temperature.Save(mTemps);
Configuration.Save(mConfigs);
[EDIT]更改了上面的预期使用代码[/EDIT]
我能想到的唯一解决方案是以下,这是不可接受的:
public class File
{
public static XElement Save(List<Temperature> temps)
{
//save temp.Value
}
public static XElement Save(List<Configuration> configs)
{
//save config.Property1
//save config.Property2
}
//etc...
}
【问题讨论】:
-
为什么方法必须是静态的?
-
我希望能够保存配置列表,而无需创建配置实例。虽然这是可能的,但似乎没有必要。
标签: c# inheritance methods static