我有一个绑定(bind)源,可以绑定(bind)到 A 列表或 B 列表。根据它是 A 还是 B,当我单击“保存”时,我想调用相应存储库的保存方法。
我能够创建这个方法来检查是否有任何列表是脏的并且需要保存:
private static bool IsDirty<T>(TList<T> list) where T : IEntity, new()
{
foreach (var entity in list)
{
if (entity.IsDirty)
return true;
}
return false;
}
但是,我遇到了以下问题:
var list = CurrentTList<A>();
和
private TList<T> CurrentTList<T>() where T: IEntity, new()
{
switch (currentRatesTable)
{
case RatesTables.A:
return (TList<T>) _bindingSourceMaster.List;
case RatesTables.B:
return (TList<T>) _bindingSourceMaster.List;
default:
return null;
}
}
这是从数据源获取当前列表的最佳方式吗?我想避免使用这样的开关,因为它对我来说不合适:
switch (currentRatesTable)
{
case Form1.RatesTables.A:
var list = CurrentTList<A>();
case Form1.RatesTables.B:
var list = CurrentTList<B>();
// ...
}
最佳答案
是的,正如 Sayse 所说,您自己需要一个接口(interface)和/或抽象类。如果有很多共享代码,你可以从后者开始。这是从一个旧的测试项目中借鉴的东西。它采用不同的方法(集合中的每个项目都是与“脏”事物相关的东西,并且有一些删除的方法可以在集合中搜索这些东西),但您应该能够根据需要进行调整:
[DataContract]
public abstract class Dirty : Object
{
protected bool _isdirty;
public bool IsDirty
{
get { return _isdirty; }
set
{
_isdirty = value;
}
}
public abstract class DataStore<T> where T : Dirty
{
private string _path;
private string _tempFile;
protected DataStore(string path, string tempfile)
{
_path = path;
_tempFile = tempfile;
}
}
因此 DataStore 拥有操作这些列表的逻辑。我的想法是,从 Dirty 继承的两个类都被序列化为 JSON,因此只要它们的成员具有正确的属性,它们就会被正确序列化,因此每个类都没有用于存储的自定义逻辑。因此,他们创建数据存储所需要做的就是:
[DataContract]
public class Account : Abstracts.Dirty
{
#region DataStore fields and singleton
private static volatile StoreClass _store = new StoreClass();
protected static StoreClass Store
{
get
{
return _store;
}
}
/// <summary>
/// Store is the data store for the Account class. This holds the active list of Accounts in a singleton, and manages the push/pull to the JSON file storage.
/// </summary>
protected class StoreClass : Abstracts.DataStore<Account>
{
#region Singleton initialization and Constructor
public StoreClass()
: base("accounts.json", "TEMP_accounts.json")
{
}
#endregion
}
}
我只从数据存储中删除了这个项目的几千行,但这太疯狂了。基本思想是将您需要的逻辑构建到 DataStore 类中以保存列表,并通过如何从 StoreClass 子级调用其构造函数来确定如何保存/加载它。
关于c# - 不同可能的子类的函数返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18106990/