在 VB.NET 中转换为 List(Of T)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4001179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:05:45  来源:igfitidea点击:

Casting to List(Of T) in VB.NET

vb.netgenericscasting

提问by CrispinH

In C# it's possible to cast to List<T>- so if you have:

在 C# 中,可以强制转换为List<T>- 所以如果你有:

List<Activity> _Activities;
List<T> _list;

The following will work:

以下将起作用:

_list = _Activities as List<T>;

but the translated line with VB.NET which is:

但是 VB.NET 的翻译行是:

_list = TryCast(_Activities, List(Of T))

throws a compilation error. So I've had a good hunt around and experimented with LINQ to find a way round this to no avail. Any ideas anyone?

引发编译错误。因此,我四处寻找并尝试了 LINQ 以找到解决此问题的方法,但无济于事。任何人的想法?

Thanks

谢谢

Crispin

克里斯平

回答by Hans Passant

I repro, this should technically be possible. Clearly the compiler doesn't agree. The workaround is simple though:

我重复,这在技术上应该是可能的。显然编译器不同意。不过解决方法很简单:

    Dim _Activities As New List(Of Activity)
    Dim o As Object = _Activities
    Dim tlist = TryCast(o, List(Of T))

Or as a one-liner:

或者作为单线:

    Dim tlist = TryCast(CObj(_Activities), List(Of T))

The JIT compiler should optimize the temporary away so it doesn't cost anything.

JIT 编译器应该优化临时的,这样它就不会花费任何费用。

回答by Jay Riggs

You can use the generic List.ConvertAllmethod.

您可以使用通用List.ConvertAll方法。

Given a List the method will return a List of a different type using a converter function you supply.

给定一个 List,该方法将使用您提供的转换器函数返回一个不同类型的 List。

The MSDN article I linked has an excellent example.

我链接的 MSDN 文章有一个很好的例子。

回答by Nate

I always use DirectCast(object, type)

我总是用 DirectCast(object, type)