在自身内部引用派生类型
本文关键字:派生 类型 引用 内部 | 更新日期: 2023-09-27 17:54:11
我有一个链接:
public abstract class Wrapper<T, TWrapped>: where TWrapped : Wrapper<T, TWrapped>
{
protected T baseObject;
protected ICollection<T> baseList;
protected ICollection<TWrapped> wrappedList;
public Wrapper (T base, ICollection<T> baseList, ICollection<TWrapped> wrappedList) { }
}
然后当我从它导出时,我需要这样做:
public class Base { }
public class Sample: Wrapper<Base, Sample> { }
是否有办法删除TWrapped
并创建对派生类型的引用?我尝试使用ICollection<Wrapped<T>>
,但后来我记得ICollection
中没有协方差。
编辑:澄清,我想要这个包装器是在对象内提供删除功能(和其他一些东西)(我不能改变基本对象,所以我需要一个包装器来提供这个功能并操纵它)。这个抽象类的方法如下:
void Remove()
{
while(this.baseList.Remove(baseObject));
this.baseList = null;
while(this.wrappedList.Remove((TWrapped)this));
this.wrappedList = null;
}
我最终改变了如何使列表同步并允许条目自行删除的逻辑。我创建了一个新类来保存包装项的集合:
public interface IWrapper<TModel>
{
TModel Model { get; }
}
public class WrapperCollection<TWrapper, TModel> : ObservableCollection<TWrapper> where TWrapper : IWrapper<TModel>
{
protected IList<TModel> modelList;
public ReadOnlyObservableCollection<TWrapper> AsReadOnly { get; private set; }
protected WrapperCollection(IList<TModel> modelList)
{
this.modelList = modelList;
AsReadOnly = new ReadOnlyObservableCollection<TWrapper>(this);
}
public WrapperCollection(IList<TModel> modelList, Func<TModel, TWrapper> newWrapper)
:this(modelList)
{
foreach (TModel model in modelList)
this.Items.Add(newWrapper(model));
}
public WrapperCollection(IList<TModel> modelList, Func<TModel, WrapperCollection<TWrapper, TModel>, TWrapper> newWrapper)
: this(modelList)
{
foreach (TModel model in modelList)
this.Items.Add(newWrapper(model, this));
}
protected override void ClearItems()
{
modelList.Clear();
base.ClearItems();
}
protected override void InsertItem(int index, TWrapper item)
{
modelList.Insert(index, item.Model);
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
modelList.RemoveAt(index);
base.RemoveItem(index);
}
protected override void SetItem(int index, TWrapper item)
{
modelList[index] = item.Model;
base.SetItem(index, item);
}
}
使用样例类:
public class wrappedInt: IWrapper<int>
{
private WrapperCollection<wrappedInt, int> list;
public Model { get; private set; }
public wrappedInt(int source, WrapperCollection<wrappedInt, int> list)
{
this.Model = source;
this.list = list;
}
public void RemoveMe()
{
if (list != null)
{
list.Remove(this);
list = null;
}
}
}
然后我可以用new WrapperCollection<wrappedInt, int>(listOfInts, (model, parent) => new wrappedInt(model, parent));
实例化一个集合。