Casting to List(Of T) in VB.NET
In C# it's possible to cast to List<T>
- so if you have:
List<Activity> _Activities;
List<T> _list;
The following will work:
_list = _Activities as List<T>;
but the translated line with VB.NET which is:
_list = Try开发者_StackOverflow社区Cast(_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?
Thanks
Crispin
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.
You can use the generic List.ConvertAll method.
Given a List the method will return a List of a different type using a converter function you supply.
The MSDN article I linked has an excellent example.
I always use DirectCast(object, type)
精彩评论