CJLeit Posted May 2, 2007 Posted May 2, 2007 Below is a sample of some code I am working with. I need to be able to declare a class as a generic object because I will load a different class based on some user selection. The code works OK but I wondering if there is a way to use the AddHandler without having to convert my object every time. If I don't put in the CType I can't compile because it tells me sampleEvent is not an event of 'Object'. I can access all my properties and methods just fine without using the CType each time but not my events. Any suggestions? Public obj As Object Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load obj = New Test obj = cType(obj, Test) AddHandler [b]CType(obj, Test).sampleEvent[/b], AddressOf junk obj.sampleProperty = "hello" End Sub Quote
Leaders snarfblam Posted May 2, 2007 Leaders Posted May 2, 2007 It is generally recommended that you turn on "Option Explicit" and "Option Strict." You are using late binding here (where the function that will be called is determined at runtime based on the type of object), which is an option that does work, but is generally looked down upon because it can allow certain types of errors in your code to go unnoticed. If you absolutely need to use late binding, you should research reflection (which has support for events), but in this case I would actually recommend that you use an interface, which also supports propertites, functions, and events. Quote [sIGPIC]e[/sIGPIC]
CJLeit Posted May 2, 2007 Author Posted May 2, 2007 The only problem I have using an interface is that some of the classes may have properties that are unique to them that I wouldn't include in the intefece. In that case would the following code be the correct way to access those properties? Thanks! Public obj As intTest Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click obj = New Test [b]CType(obj, Test).sampleProperty = "hello"[/b] AddHandler obj.testEvent, AddressOf testEvent End Sub Quote
Administrators PlausiblyDamp Posted May 2, 2007 Administrators Posted May 2, 2007 If the objects are so different they can't have a consistent interface then you are always going to encounter problems in this kind of situation. Personally though I would still define relevant Interface(s) where possible and use it (them) rather than just using object as a datatype, if you need to access properties not defined in the interface then you would still need to cast the variable to the correct type - but at least the cast wouldn't be required in as many places. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.