英文:
Unable to cast to object
问题
我有一个代码:
var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
var list = new List<IBO>(result.OfType<IBO>());
但我需要能够向列表中添加许多元素。我尝试过:
var list = new List<IBO>();
var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
list.Add((IBO)result.OfType<IBO>());
这导致错误:
无法将类型为 ''<OfTypeIterator>d__95`1[BO.IBO]'' 的对象转换为类型 ''BO.IBO''。
如何解决这个问题?
英文:
I had a code:
var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
var list = new List<IBO>(result.OfType<IBO>());
But I need to be able to add many elements in a list. I tried:
var list = new List<IBO>();
var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
list.Add((IBO)result.OfType<IBO>());
Which results in an error:
Unable to cast object of type '<OfTypeIterator>d__95`1[BO.IBO]' to type 'BO.IBO'.
How to resolve this?
答案1
得分: 3
"OfType"将返回一个集合:IEnumerable<TResult>。问题在于,您试图将整个集合转换为单个元素。因此出现错误消息。
转换已经由"OfType"调用执行。您需要使用不同的添加方法。它被称为AddRange。
> 将指定集合的元素添加到List<T>的末尾。
list.AddRange(result.OfType<IBO>());
英文:
OfType
will return a collection: IEnumerable<TResult>. The problem is that you try to cast this entire collection to a single element. Hence the error message.
The cast is already performed by the OfType
call. You would need a different adding method. It is called AddRange.
> Adds the elements of the specified collection to the end of the List<T>.
list.AddRange(result.OfType<IBO>());
答案2
得分: 1
第二个代码片段应使用 AddRange
,无需额外转换为 IBO
:
> 将指定集合的元素添加到 List<T>
的末尾。
var list = new List<IBO>();
var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
list.AddRange(result.OfType<IBO>());
请注意,这两个代码片段将执行相同的操作。如果只有一个源集合,只需使用第一个。
英文:
The second snippet should use AddRange
without extra casting to IBO
:
> Adds the elements of the specified collection to the end of the List<T>
.
var list = new List<IBO>();
var result = BOBase.Search(Mapper.SourceBrowserType, searchCriteria);
list.AddRange(result.OfType<IBO>());
Note that both snippets will doe the same. If you have only one source collection then just use the first one.
答案3
得分: 0
只需使用期望一个 IEnumerable<IBO>
参数的构造函数,无需额外的 Add***
调用:
var list = new List<IBO>(result.OfType<IBO>());
但我需要能够在列表中添加许多元素。
实际上,上述代码正是如此:它将指定类型的所有元素添加到您新创建的列表中。
或者可以使用以下方式:
var list = result.OfType<IBO>().ToList();
英文:
You don't need an extra Add***
-call, just use the constructor that expects an IEnumerable<IBO>
:
var list = new List<IBO>(result.OfType<IBO>());
> But I need to be able to add many elements in a list.
In fact the above does exactly that: it adds all the elements of the specified type into your newly created list.
Alternativly use this:
var list = result.OfType<IBO>().ToList();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论