将VB6代码转换为VB.NET时,我遇到了一些问题。我会在这里特别处理一个。
原始的VB6代码是:
Public Sub dynForm(sFormName As String, loadingForm As Form, Optional resizeMe As Boolean = True)
On Error GoTo ErrHandler
'Used to dynamically open a form based on its name.
Dim oForm As Form
'Add a Form to the collection
Set oForm = Forms.Add(sFormName)
'Load the Form
Load oForm
If resizeMe Then
setFrmSize oForm
End If
centerForm oForm
'Show The Form
oForm.Show 1, loadingForm
If oForm Is Nothing Then Exit Sub
Set oForm = Nothing
Exit Sub
ErrHandler:
logError Err.Description & vbCrLf & "sFrm:" & sFormName & " not found!", Err.Number, "common.dynForm", ErrorMsg
End Sub
转换过程产生以下结果(我缩短了转换注释,这些注释引用了不再有效的链接):
Public Sub dynForm(ByRef sFormName As String, ByRef loadingForm As System.Windows.Forms.Form, Optional ByRef resizeMe As Boolean = True)
On Error GoTo ErrHandler
'Used to dynamically open a form based on its name.
Dim oForm As System.Windows.Forms.Form
'Add a Form to the collection
'UPGRADE_ISSUE: Forms method Forms.Add was not upgraded.
oForm = Forms.Add(sFormName)
'Load the Form
'UPGRADE_ISSUE: Load statement is not supported.
Load(oForm)
If resizeMe Then
setFrmSize(oForm)
End If
centerForm(oForm)
'Show The Form
VB6.ShowForm(oForm, 1, loadingForm)
If oForm Is Nothing Then Exit Sub
'UPGRADE_NOTE: Object oForm may not be destroyed until it is garbage collected.
oForm = Nothing
Exit Sub
ErrHandler:
logError(Err.Description & vbCrLf & "sFrm:" & sFormName & " not found!", Err.Number, "common.dynForm", ErrorType.ErrorMsg)
End Sub
返回以下错误:
名称'Forms'未声明。
名称'Load'未声明。
我刚刚注释掉了Load语句。但是,将这种形式添加到该系列已被证明是一个更难以破解的坚果。
我尝试了几种变体:
oForm = System.Windows.Forms.Form.Add(sFormName)
返回错误:'Add'不是'System.Windows.Forms.Form'的成员
oForm = System.Windows.Forms.Form.AddOwnedForm(sFormName)
返回错误:对非共享成员的引用需要对象引用。
oForm = My.Forms.Add(sFormName)
返回错误:“添加”不是“RSC_Reports.My.MyProject.MyForms”的成员。
如何将表单名称作为添加到集合的参数传递?
答案 0 :(得分:1)
VB6代码正在使用类名创建表单的新实例。 VB.Net这样做的方法就是反思。
尝试将此代码from here与编辑一起使其不区分大小写。
Imports System
Imports System.Windows.Forms
Imports System.Reflection
Public Class ObjectFinder
Public Shared Function CreateObjectInstance(ByVal objectName As String) As Object
' Creates and returns an instance of any object in the assembly by its type name.
Dim obj As Object
Try
If objectName.LastIndexOf(".") = -1 Then
'Appends the root namespace if not specified.
objectName = [Assembly].GetEntryAssembly.GetName.Name & "." & objectName
End If
obj = [Assembly].GetEntryAssembly.CreateInstance(objectName, True)
Catch ex As Exception
obj = Nothing
End Try
Return obj
End Function
Public Shared Function CreateForm(ByVal formName As String) As Form
' Return the instance of the form by specifying its name.
Return DirectCast(CreateObjectInstance(formName), Form)
EndFunction
然后更换你的线。
oForm = Forms.Add(sFormName)
使用此行
oForm = ObjectFinder.CreateForm(sFormName)