C# - 可以列表< MyClass>被无缝地转换为List< Interface>或类似?
我在我的控制中有一个 DataSource
,总是列表
其中 T
必须继承 IEntity
。
I have a DataSource
in my control which is always a List<T>
where T
has to inherit from IEntity
.
public class MyClass<T> where T : IEntity
{
public List<T> DataSource
{
get;
set;
}
}
现在, c $ c>列出< T> 至列表< IEntity>
执行以下操作:
Now, obviously you can't cast a List<T>
to a List<IEntity>
doing the following:
List<IEntity> wontWork = (List<IEntity>)this.DataSource;
如何获取DataSource作为 IEntity
,同时仍然能够从 DataSource
中添加和删除项目?也就是说我可以做以下,但从列表中删除它返回不会从DataSource中删除:
How can I get the DataSource as a List of IEntity
, whilst still being able to add and remove items from the DataSource
? I.e. I could do the following, but removing from the List it returns would not remove from the DataSource:
public List<TOut> GetDataSourceCopyAsUnderlyingType<TOut>()
{
if (this.DataSource == null)
{
return new List<TOut>();
}
else
{
// Get the list and the enumerator
IList list = (IList)this.DataSource;
IEnumerator enumerator = list.GetEnumerator();
// Build the target list
List<TOut> targetList = new List<TOut>();
int i = 0;
while (enumerator.MoveNext())
{
TOut entity = (TOut)list[i];
targetList.Add(entity);
i++;
}
return targetList;
}
}
需要一些方法来执行以下操作:
Basically, I need some way of doing the following:
List<IEntity> interfaceList = this.GetDataSourceAsAnotherType<IEntity>();
int dataSourceCount = this.DataSource.Count; // Equals 5
int interfaceCount = interfaceList.Count; // Equals 5
interfaceList.RemoveAt(0);
int dataSourceCount = this.DataSource.Count; // Equals 4
int interfaceCount = interfaceList.Count; // Equals 4
只是为了添加,我不介意,使用不同的类型,而不是列表。
And just to add, I don't mind if it means I've got to use a different type instead of a List.
编辑:对不起,忘了说我使用.Net2.0,到.Net 3.5。
EDIT: Sorry, forgot to say I'm using .Net2.0 and cannot move to .Net 3.5.
如果允许这将是一个巨大的坏主意,这就是为什么它不是。我可以将任何旧的IEntity添加到 List< IEntity>
,如果该IEntity不能被转换为T,那么该IEntity将会爆炸。虽然所有Ts是IEntity,但并非所有IEntity
It would be a monumentally bad idea if this were allowed, which is why it isn't. I can add any old IEntity to a List<IEntity>
which will blow up if that IEntity can't be cast to T. Whilst all Ts are IEntities, not all IEntities are Ts.
这适用于数组,因为数组有一个有意的子类型洞(就像在Java中一样)。集合没有子类型洞。
This works with arrays because arrays have a deliberate subtyping hole (as they do in Java). Collections do not have a subtyping hole.