开发者

VB.NET syntax and string Extension Methods

Code in VB.NET

Module Utils
<Runtime.CompilerServices.Extension()> _
Public Sub Print(ByVal message As String)
    Console.WriteLine(message)
End Sub
End Module

Public Class Foo
Public Sub New()
    Dim test = "cucu"
    test.Print() ' no problem: custom string extension method '
    "cucu".Print() ' syntax error '
End Sub开发者_开发知识库
End Class

1) First problem, I'd prefer to be able to use "cucu".MyExtensionMethod() as well as test.MyExtensionMethod();

1') Syntax like

  "No Result".Print() ' Print is an extension method '
  " No Result ".Trim() ' Trim is a framework method '

does not work both of them

However, syntax like

  myTextBox.Text = "No Result".Translate() ' Translate is an extension method '
  myTextBox.Text = " No Result ".Trim() ' Trim is a framework method '

works very well.

So seems some consistency miss of the string constant behavior.

2) Have a look on the COMMENTS (in the attached picture). The words "custom", "string" and "error" are highlighted, however they are in the comments, so should be green, not blue.

Why this? What workaround?

EDIT:

Declared as "bug" in Microsoft Connect (even if is not more that a syntactic "miss")...

EDIT 2:

As remarked Hans Passant, standard string methods, like "cucu".Trim() does not work either.


I can confirm this is indeed a “bug” (tested in Visual Studio 2008). But in fact, it’s by design in VB and won’t be changed.

However, I’d like to take the time to explain why this is a horrible question. Sorry Serhio.

  1. It doesn’t list all steps necessary to reproduce the problem.
  2. It doesn’t provide the complete code.
  3. It doesn’t reduce the problem to the minimal (don’t use Infer here – it detracts from the problem)
  4. As a consequence, there are a hundred different reasons that would completely explain this behaviour, without a bug (for an example, see stakx’ excellent (now deleted) answer).

Here’s a complete example, using the default settings for VB, that doesn’t have these problems (create a new empty console project solution and paste this code into Module1.vb):

Module Extensions
    <System.Runtime.CompilerServices.Extension()> _
    Public Sub ShowDialog(ByVal message As String)
        Console.WriteLine(message)
    End Sub
End Module

Module Module1
    Sub Main()
        Dim s As String = "Hello"
        s.ShowDialog()
        ' Doesn’t work:
        '"World".ShowDialog()
        ' Works:
        Call "World".ShowDialog()
    End Sub
End Module

The behaviour is consistent in VB: you cannot have a value as the first token in a logical line. For instance, the following code also doesn’t compile (given an existing, appropriate, definition of a form class Form1):

New Form1().ShowDialog()

and once again the fix is to prefix the expression by Call:

Call New Form1().ShowDialog()


You can do CStr("cucu").ShowDialog()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜