Rob*_*b3C 0 vb.net inheritance winforms
I have inherited (look at that, a pun, sorry...) a suite of VB.Net applications which share common functionality, currently "copy and paste" duplicated across all of them. I want to begin the refactoring process. Side note: I am primarily a C# developer, not too familiar with VB.
All of these VB applications are using the "Application Framework". One of the first things I tried to do is get all of them to inherit from a common application base class. I created a new class:
Namespace My
Public Class ParentApplicationBase
Inherits Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
Public Sub Bar()
Console.WriteLine("Here we are in Bar()")
End Sub
End Class
End Namespace
Run Code Online (Sandbox Code Playgroud)
Then, in ApplicationEvents.vb, ChildApp.vb, and Application.Designer.vb, I changed the
Partial Friend MyApplication
Run Code Online (Sandbox Code Playgroud)
to
Partial Friend MyApplication : Inherits ParentApplicationBase
Run Code Online (Sandbox Code Playgroud)
However, that results in the error:
Base class 'ParentApplicationBase' specified for class 'MyApplication' cannot be different from the base class 'Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase' of one of its other partial types.
I have double and tripled checked that all of my partial classes are indeed inheriting from ParentApplicationBase. It almost seems like there is some other "hidden" place in the magic of the application framework that is making it think the base class is WindowsFormsApplicationBase rather than ParentApplicationBase.
I have searched both the general web and Stackoverflow in vain. The closest I found was this question VB.NET - How do you change the namespace/class names for a "Windows application" from the default My.MyApplication?, but that did not help.
在此先感谢您的任何建议!
当您启用应用程序框架时,VB.NET 编译器会自动生成代码。它声明了 My.MyApplication 类并从 WindowsFormsApplicationBase 派生它。您看不到此代码,它仅作为 MSIL 存在,您必须使用反编译器(如 ildasm)才能看到它。
但是正如错误告诉您的那样,自动生成的 My.MyApplication 已经固定了基类,您无法再更改它。获得成功的唯一方法是禁用应用程序框架。没什么好担心的,该类的主要作用是使项目的应用程序属性选项卡的设置起作用,您可以使用代码简单地更改它们。
项目 > 属性 > 应用程序选项卡 > 取消选中“启用应用程序框架”复选框。启动对象 > “Sub Main”。添加一个新模块并使其看起来类似于:
Module Entrypoint
Sub Main(args As String())
Application.SetCompatibleTextRenderingDefault(False)
Dim app = New MyApplicationFramework()
app.Run(args)
End Sub
End Module
Class MyApplicationFramework
Inherits ApplicationServices.WindowsFormsApplicationBase
Public Sub New()
MyBase.New(ApplicationServices.AuthenticationMode.Windows)
Me.EnableVisualStyles = True
Me.IsSingleInstance = False
Me.SaveMySettingsOnExit = True
Me.ShutdownStyle = ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = New Form1
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
它使用与“应用程序”选项卡中的默认设置相同的值。根据需要进行调整。并更改基类。