Calling Class from another File ASP.NET VB.NET
Lets say I have a class like this in class1.vb:
Public Class my_class
Public Sub my_sub()
Dim myvar as String
myvar = 10
Session("myvar") = myvar
End Sub
End Class
Then I have a ASP.NET page with a code-behind file, default.aspx and default.aspx.vb and I want to call my_class. I'm doing the following, but it doesn't work:
Imports my_app.my_class
Partial Public Class _default
Inherits System.Web.UI.Page
Protect开发者_Go百科ed Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load
my_class()
End Sub
End Class
I get a "Reference to a non-shared member requires an object reference"
Try importing the namespace that contains the class, not the class itself.
So instead of this:
Imports my_app.my_class
do this:
Imports my_app
VB.NET imports namespaces into the file scope to help the compiler resolve type names that aren't fully qualified. This means you are free to use all types declared in the my_app
namespace in this code file without prefixing the type name with my_app
.
Okay, once you have done that you will need to do switch up the contents of Page_Load
to create an instance of my_class
like this:
Dim foo As New my_class
my_class.my_sub()
Now you have an instance of my_class
called foo
and you can call instance methods on it.
The other thing you could do is make my_sub
a Shared
method so you don't have to create an instance:
Public Shared Sub my_sub()
If you do this then you do not need to create an instance of my_class
to call my_sub
- you can call my_sub
directly:
my_class.my_sub()
Imports my_app.my_class
Partial Public Class _default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load
Dim myClass as new my_class()
myClass.my_sub()
End Sub
End Class
Do you mean you want to call my_sub() on my_class? You can either mark it as a shared methog so that it can be called as my_class.my_sub()
or
instantiate an instance of it:
Dim myclass as new my_class()
myclass.my_sub()
精彩评论