C#-列表< MyClass>可以吗?无缝转换为List< Interface>或类似的? [英] C# - Can a List<MyClass> be seamlessly cast to a List<Interface> or similar?
问题描述
我的控件中有一个 DataSource
,它始终是 List< T>
,其中 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;
}
}
现在,显然您不能投射 List< T>
到 List< IEntity>
的操作如下:
Now, obviously you can't cast a List<T>
to a List<IEntity>
doing the following:
List<IEntity> wontWork = (List<IEntity>)this.DataSource;
如何获取数据源作为 IEntity $ c的列表$ c>,同时仍然能够从
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
而且,我不介意是否有
编辑:抱歉,忘记了说我正在使用.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,则会爆炸。尽管所有T是IEntities,但并非所有IEntities都是Ts。
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.
这篇关于C#-列表< MyClass>可以吗?无缝转换为List< Interface>或类似的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!