2

我有两种具有多对多关系的抽象类型:

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集合中Sample

当我尝试将一个实例添加Experiment<T>到一个集合中时,问题就出现了List<Experiment<Sample>>。由于T是 的子类型Sample,我假设不会有问题。实际发生的情况如下:

Value of type 'Experiment<T>' cannot be converted to 'Experiment<Sample>`

我的问题是是否有办法解决这个问题,或者更好地模拟这些实体之间的关系。

4

2 回答 2

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());
于 2013-07-22T18:02:08.933 回答
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; }
    }
}

因为这两种类型相互依赖,所以它们需要共享相同的泛型类型。

于 2013-07-22T18:09:53.640 回答