vb.net windows forms question. I've got 3 forms that have exactly the same functions, so I decided to create an interface.
public Interface IExample
public sub Add()
Public sub Edit()
Public sub View()
End Interface
Then I created the 3 forms, and added the 'implements interface IExample' to each.
public class frmExample1
implements Interface IExample
Same for frmExample2
, frmExample3
Finally, in code, I declare a variable of the inter开发者_StackOverflow社区face type .. Dim objfrmExample as IExample
then ...
objFrmExample = frmExample2
At this point, objfrmExample is now instantiated, even though I've not done a "objfrmExpample = new [what-goes-here?] " and I'm curious as to why.
I could possibly guess that because you cannot instantiate an interface variable, then vb.net automatically creates an instance. But thats just a guess. The question is , what is meant by declaring a variable of type Interface, and how does it work?
Anyway, just curious :-)
At this point, objfrmExample is now instantiated, even though I've not done a "objfrmExpample = new [what-goes-here?] " and I'm curious as to why.
This has nothing to do with interfaces. You can always treat a form class name in VB as though it were an instance. The reason is that the VB compiler creates properties of all your forms inside My.Forms
. Now you can access a “default” instance of each form by accessing My.Forms.<FormName>
.
Now comes the ugly part: you can also omit My.Forms.
. In other words, whenever you write just FormName
and from the context it’s unambiguous that you need an instance rather than the class name, VB will act as though you’d written My.Forms.<FormName>
.
Luckily, this only works for forms, not for any other classes. VB creates each default instance when you first access it. So as long as you don’t access a default instance, it’s not created. Once you access it for the first time, VB creates it and invokes its constructor.
When you declare a variable of type interface you can work with any object that implements the interface. Therefore when setting a variable that is of an interface type equal to a class that implements the interface an implicit cast is done. For example.
Dim oExample as IExample
dim testForm as MyTestForm
oExample = MyTestForm
Now, this is the way that you do it, you can do an explicit cast this way
Dim oExample as IExample
Dim testForm as MyTestForm
oExample = CType(MyTestForm, IExample)
For your specific example with VB.NET and an un-instantiated form this is due to a VB "feature" that auto-creates an instance of the form.
精彩评论