本文介绍了未知类型的VB.NET通用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在其中一种方法中,我需要未指定的泛型类型的公共类SWTTField(Of dataType)的变量,仅当类型时才会实例化是已知的。但是,我不能创建一个变量 Dim f As SWTTField ,因为它给了我一个错误对于SWTTField(Of dataType)的几个类型参数, code>。如何延迟指定泛型变量的类型,但仍然有一个变量? 为了做到这一点,你还需要使得使用它的类是通用的。例如,假设您有一个使用通用列表的类,如下所示: 公共类注册表私有_items As New List(Of Object)() Public Sub Register(item As Object) _items.Add(item) End Sub End Class 但你不希望它是 List(Of Object) code>。相反,你希望它是一个 List(Of?),它将是一个特定类型的列表,但你想在其他地方指定类型。在这种情况下,你只需要让外部类也是通用的,就像这样: 公共类注册表(Of T)私人_项目作为新列表(T)() 公共小组注册(项目为T) _items.Add(项目)结束Sub End Class 然后,当您使用 Registry class,你将不得不指定它注册的项目的类型: Dim x作为新的注册表(用户)() In one of the methods, I need variable of unspecified generic type Public Class SWTTField(Of dataType) that will be instantiated only when type of dataType is know. However, I can't create a variable Dim f As SWTTField because it gives me an error To few type arguments to SWTTField(Of dataType). How do I delay specifying type of generic variable, but still have a variable ? 解决方案 In order to do that, you need to also make the class that uses it be generic. For instance, let's say you had a class that used a generic list, like this:Public Class Registry Private _items As New List(Of Object)() Public Sub Register(item As Object) _items.Add(item) End SubEnd ClassBut you didn't want it to be a List(Of Object). Instead, you wanted it to be a List(Of ?) where it would be a list of some specific type, but you wanted to specify the type later elsewhere. In a case like that, you'd just need to make the outer class be generic too, like this:Public Class Registry(Of T) Private _items As New List(Of T)() Public Sub Register(item As T) _items.Add(item) End SubEnd ClassThen, when you use the Registry class, you'd be forced to specify the type of the items that it registers:Dim x As New Registry(Of User)() 这篇关于未知类型的VB.NET通用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!