具有Open Type参数的类型集合

时间:2013-05-30 04:35:25

标签: c# collections typed

我想知道为什么如果我写下面的陈述我会收到错误,虽然我在课堂上提到什么是T

IList<T> targetObjectsCollection = new List<T>();
for (int counter = 0;  counter < dataTransferObjects.Count; counter++)
{
    targetObjectsCollection.Add(MappSharePointDAOToDTO(sharePointDaos[counter], dataTransferObjects[counter]));
}

当我将其更改为以下语句时,错误已经消失了?

IList<IMapperMarker> targetObjectsCollection = new List<IMapperMarker>();
for (int counter = 0;  counter < dataTransferObjects.Count; counter++)
{
    targetObjectsCollection.Add(MappSharePointDAOToDTO(sharePointDaos[counter], dataTransferObjects[counter]));
}
任何人都可以描述。

1 个答案:

答案 0 :(得分:3)

您似乎没有定义T。这是一个占位符。它需要定义。

如果在T有定义的上下文中使用此代码,则此代码可能有效。例如,

private IList<T> AddDataTransferObjects(IList<T> dataTransferObjects)
    : where T : IMapperMarker
{
    IList<T> targetObjectsCollection = new List<T>();
    for (int counter = 0;  counter < dataTransferObjects.Count; counter++)
    {
        targetObjectsCollection.Add(MappSharePointDAOToDTO(sharePointDaos[counter], dataTransferObjects[counter]));
    }
    return targetObjectsCollection;
}

如果你这样称呼如下:

IList<IMapperMarker> dtoList = Something();
var list = AddDataTransferObjects(dtoList);

在这种情况下,内部T将绑定到IMapperMarker类型。