是否也可以创建接口和抽象类的匿名对象?
例如,在Scala中,我可以这样做:trait Something {
val someProperty: Int
}
val mySomething = new Something() {
override val someProperty: Int = 42
}
这在VB.net中也是可能的吗?如果是,我该怎么做?
搜索这个问题没有产生任何可用的结果,或者我只是没有击中正确的关键字。我得到的唯一结果是关于匿名类型的,比如这个文档页面和MSDN上的这个教程。但是,当我执行以下操作时,这似乎不像预期的那样工作:
Public MustInherit Class Something
Public MustOverride ReadOnly Property SomeProperty as Integer
End Class
和我想使用它的地方:
Dim mySomething As New Something
With mySomething
' I expect to provide an implementation for the property here
End With
编译器报错'New' cannot be used on a class that is declared 'MustInherit'
.
是这样的方法不可能在VB.net或我做错了什么?
不,在VB中,如果你想要一个实现接口或继承特定基类的类,那就由你自己来定义这样的类。
你已经找到了最接近的特性——匿名类型——但是你不能选择它们的基类型,也不能让它们实现任何接口。