是否可以从VB.NET中的抽象类/接口创建匿名对象?

时间:2015-07-29 07:59:49

标签: .net vb.net

是否也可以创建接口和抽象类的匿名对象?

例如,在Scala中,我可以这样做:

trait Something {

  val someProperty: Int
}

val mySomething = new Something() {

  override val someProperty: Int = 42
}

这在VB.net中是否可行,如果是,我该怎么做?

搜索此问题并未产生任何可用的结果,或者我没有点击正确的关键字。我得到的唯一结果是关于MSDN上的this documentation pagethis tutorial等匿名类型。但是,当我执行以下操作时,这似乎并不像预期的那样有效:

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中是不可能的,还是我做错了什么?

1 个答案:

答案 0 :(得分:2)

不,在VB中,如果你想要一个实现接口或继承自特定基类的类,那么你可以实际定义这样一个类。

您已经找到了最近的功能 - 匿名类型 - 但您无法选择其基本类型,也无法实现任何接口。