vb.net 我可以将类引用作为参数传递给 VBNet 中的函数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17007177/
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
Can I pass a class reference as a parameter to a function in VBNet?
提问by mindofsound
Please forgive me if I use improper terminology or sound like a complete noob.
如果我使用了不正确的术语或听起来像一个完全的菜鸟,请原谅我。
When calling a sub in a class library, I'd like to pass not an instantiated form, but just a reference to the class that represents the form. Then I want to instantiate the form from within the class library function. Is this possible?
在类库中调用 sub 时,我不想传递实例化的表单,而只想传递对表示表单的类的引用。然后我想从类库函数中实例化表单。这可能吗?
Something like the following:
类似于以下内容:
In the main application:
在主应用程序中:
ClassLib.MyClass.DisplayForm(GetType(Form1))
Then, in the class library:
然后,在类库中:
Public Class MyClass
Public Shared Sub DisplayForm(WhichFormClass As Type)
Dim MyForm as Form = WhichFormClass.CreateObject() 'Getting imaginitive
MyForm.ShowDialog()
End Sub
End Class
Hopefully my example conveys what I'm trying to accomplish. If you think my approach is bogus, I'm open to alternative strategies.
希望我的例子传达了我想要完成的事情。如果您认为我的方法是虚假的,我愿意接受替代策略。
回答by Nico Schertler
Additionally to MotoSV's answer, here is a version that uses only generics:
除了 MotoSV 的回答之外,这里还有一个仅使用泛型的版本:
Public Shared Sub DisplayForm(Of T As {New, Form})()
Dim instance = New T()
instance.ShowDialog()
End Sub
Which you can use like:
您可以使用以下方法:
DisplayForm(Of Form1)()
With this approach you can be sure that the passed type is a form and that the instance has the ShowDialog()method. There is no cast necessary that might fail eventually. However, it is necessary to know the type parameter at design time in order to call the method.
使用这种方法,您可以确保传递的类型是一个表单并且实例具有该ShowDialog()方法。没有必要的演员可能最终失败。但是,必须在设计时知道类型参数才能调用该方法。
回答by MotoSV
Try
尝试
Dim classType As Type = GetType(Form1)
Then call the method:
然后调用方法:
DisplayForm(classType)
You can then use this type information and reflection to create an instance at runtime in the DisplayForm method:
然后,您可以使用此类型信息和反射在 DisplayForm 方法中在运行时创建实例:
Activator.CreateInstance(classType)
Note that this is a simple example and performs no error checking, etc. You should read a bit more on reflection to make sure you handle any potential problems.
请注意,这是一个简单的示例,不执行错误检查等。您应该阅读更多关于反射的内容,以确保您处理任何潜在问题。
Edit 1:
编辑1:
Simple example:
简单的例子:
Public Class MyClass
Public Shared Sub DisplayForm(ByVal formType As Type)
Dim form As Form = DirectCast(Activator.CreateInstance(formType), Form)
form.ShowDialog()
End Sub
End Class
You use the method as:
您使用该方法:
Dim formType As Type = GetType(Form1)
MyClass.DisplayForm(formType)
Again, best to perform some error checking in all of this.
同样,最好在所有这些中执行一些错误检查。

