在 Visual Basic.NET 中构造一个对象而不分配它 [英] Constructing an object without assigning it in Visual Basic.NET
问题描述
我已经使用 VB.net 好几年了,但不断遇到我不知道如何解决的小怪癖.好奇心终于战胜了我,所以我现在问:有没有办法在不分配对象的情况下创建对象?
I've used VB.net for several years now, but keep coming across little quirks that I don't know how to work around. Curiosity finally got the best of me, so I ask now: is there a way to create an object without assigning it?
例如,假设我有一个 Engine 类,我想实例化它并让它立即执行它需要执行的任何操作.如果在创建 Engine 之后我不需要对它做任何事情,那么到目前为止,我已经做了类似的事情:
For example, say I have an Engine class, that I want to instantiate and have it immediately do whatever it needs to do. If there's nothing I need to do with Engine after creating it, I have, till now, done something like:
将 myEngine 调暗为 new Engine()
有没有办法避免dim myEngine as"部分?你当然可以在 Java 中.我可以在 Java 中使用new Engine()"创建一个对象,而不将其分配给任何东西.
Is there a way to avoid the "dim myEngine as" part? You certainly can in Java. I could just create an object with "new Engine()" in java and not assign it to anything.
我为什么需要这个?因为我经常想创建一个执行某些功能的委托对象(因此我称它为引擎"),否则我不需要引用它.我曾经让这样的对象有一个公共子执行",但发现它很麻烦——我宁愿只创建对象而不用担心记住调用它的执行方法.而且我发现创建对我不打算使用的对象的引用在美学上令人不快.
Why do I need this? Because often I want to create a delegate object (hence I called it "engine") that performs some functionality, but otherwise I don't need to ever reference it. I used to have such objects have a "public sub perform", but have found that cumbersome -- I'd rather just create the object and not worry about remembering to call its perform method. And I find it aesthetically displeasing to create references to objects that I don't intend to use.
任何 VB 大师有什么建议吗?
Any VB guru have a suggestion?
谢谢,
--迈克尔
推荐答案
为此,您需要将 New 声明放在括号 ( ) 内
To do this you need to put the New declaration inside Parentheses ( )
你可以试试这个语法:
you can try this syntax:
Call New TheClass().Method1()
或:
DoSomething(New TheClass())
甚至:
DoSomething(New TheClass().GetStringData())
来源:http://tutorials.beginners.co.uk/vb-net-programming-part-6-interacting-with-objects.htm
这篇关于在 Visual Basic.NET 中构造一个对象而不分配它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!