我有两种具有多对多关系的抽象类型:
public abstract class Experiment<T> where T : Sample
{
private List<T> _Samples = new List<T>;
public IReadOnlyCollection<T> Samples {
get { return _Samples.AsReadOnly(); }
}
public void AddSample(T sample)
{
_Samples.Add(sample);
sample.Experiments.Add(this); // The problem lies here
}
}
public abstract class Sample
{
private List<Experiment<Sample>> _Experiments = new List<Experiment<Sample>>;
public ICollection<Experiment<Sample>> Experiments {
get { return _Experiments; }
}
}
如您所见,实验接受的类型参数是Sample
的子类。我想要做的是:每当Sample
的子类型的实例添加到Experiment
时,Experiment
应相应地添加到Experiments
的{{1}}集合中Sample
。
当我尝试将Experiment<T>
的实例添加到List<Experiment<Sample>>
的集合时,会出现问题。由于T
是Sample
的子类型,我假设不存在问题。实际发生的是以下内容:
Value of type 'Experiment<T>' cannot be converted to 'Experiment<Sample>`
我的问题是,是否有办法解决这个问题,或者更好地模拟这些实体之间的关系。
答案 0 :(得分:2)
public class Experiment<T> where T : Sample
{
private List<T> _Samples = new List<T>();
public IReadOnlyCollection<T> Samples
{
get { return _Samples.AsReadOnly(); }
}
public Experiment()
{
}
public Experiment(IEnumerable<T> samples)
{
_Samples = samples.ToList();
}
public void AddSample(T sample)
{
_Samples.Add(sample);
sample.Experiments.Add(new Experiment<Sample>(_Samples)); // The problem lies here
}
}
public abstract class Sample
{
private List<Experiment<Sample>> _Experiments = new List<Experiment<Sample>>();
public ICollection<Experiment<Sample>> Experiments
{
get { return _Experiments ; }
}
}
通过添加一些构造函数并修改Experiments
中的Sample
集合,我认为我能够实现您正在寻找的东西。现在您可以使用以下代码
public class MySample : Sample{}
public class MyExperiment : Experiment<MySample>{}
MyExperiment me = new MyExperiment();
me.AddSample(new MySample());
答案 1 :(得分:2)
所以我认为修复就是这样:
public abstract class Experiment<T> where T : Sample<T>
{
private List<T> _Samples;
public IReadOnlyCollection<T> Samples {
get { return _Samples.AsReadOnly(); }
}
public void AddSample(T sample)
{
_Samples.Add(sample);
sample.Experiments.Add(this); // The problem lies here
}
}
public abstract class Sample<T> where T : Sample<T>
{
private List<Experiment<T>> _Experiments;
public ICollection<Experiment<T>> Experiments {
get { return _Experiments; }
}
}
因为这两种类型相互依赖,所以它们需要共享相同的泛型类型。