IT story

VB.NET의 여러 줄 문자열

hot-time 2020. 6. 23. 07:22
반응형

VB.NET의 여러 줄 문자열


파이썬과 같은 VB.NET에서 여러 줄 문자열을 갖는 방법이 있습니까?

a = """
multi
line
string
"""

아니면 PHP?

$a = <<<END
multi
line
string
END;

물론 그렇지 않은 것

"multi" & _
"line

XML 리터럴사용 하여 비슷한 효과를 얻을 수 있습니다 .

Imports System.XML
Imports System.XML.Linq
Imports System.Core

Dim s As String = <a>Hello
World</a>.Value

특수 문자가있는 경우 CDATA 블록을 사용해야합니다.

Dim s As String = <![CDATA[Hello
World & Space]]>.Value

2015 년 업데이트 :

여러 줄 문자열 리터럴은 Visual Basic 14 ( Visual Studio 2015 ) 도입되었습니다 . 위의 예는 이제 다음과 같이 쓸 수 있습니다.

Dim s As String = "Hello
World & Space"

MSDN article isn't updated yet (as of 2015-08-01), so check some answers below for details.

VB-14 Github 저장소에 Roslyn New-Language-Features 기능 이 추가되었습니다 .


VB.Net에는 그러한 기능이 없으며 Visual Studio 2010에서는 제공 되지 않을 것입니다. jirwin이 참조하는 기능을 암시 적 라인 연속이라고합니다. 여러 줄로 된 문장이나 표현식에서 _를 제거하는 것과 관련이 있습니다. 이렇게하면 _로 여러 줄 문자열을 종료 할 필요가 없지만 VB에는 여전히 여러 줄 문자열 리터럴이 없습니다.

여러 줄 문자열의 예

Visual Studio 2008

Dim x = "line1" & vbCrlf & _
        "line2"

Visual Studio 2010

Dim x = "line1" & vbCrlf & 
        "line2"

이 변형을 사용했습니다.

     Dim query As String = <![CDATA[
        SELECT 
            a.QuestionID
        FROM 
            CR_Answers a

        INNER JOIN 
            CR_Class c ON c.ClassID = a.ClassID
        INNER JOIN
            CR_Questions q ON q.QuestionID = a.QuestionID
        WHERE 
            a.CourseID = 1
        AND 
            c.ActionPlan = 1
        AND q.Q_Year = '11/12'
        AND q.Q_Term <= (SELECT CurrentTerm FROM CR_Current_Term)
    ]]>.Value()

문자열에서 <>를 허용합니다.


Visual Studio 2015부터 여러 줄 문자열을 사용할 수 있습니다.

Dim sql As String = "
    SELECT ID, Description
    FROM inventory
    ORDER BY DateAdded
"

유용성을 극대화하기 위해 문자열 보간 과 결합 할 수 있습니다 .

Dim primaryKey As String = "ID"
Dim inventoryTable As String = "inventory"

Dim sql As String = $"
    SELECT {primaryKey}, Description
    FROM {inventoryTable}
    ORDER BY DateAdded
"

Note that interpolated strings begin with $ and you need to take care of ", { and } contained inside – convert them into "", {{ or }} respectively.

Here you can see actual syntax highlighting of interpolated parts of the above code example:

enter image description here

If you wonder if their recognition by the Visual Studio editor also works with refactoring (e.g. mass-renaming the variables), then you are right, code refactoring works with these. Not mentioning that they also support IntelliSense, reference counting or code analysis.


Multiline string literals are introduced in Visual Basic 14.0 - https://roslyn.codeplex.com/discussions/571884

You can use then in the VS2015 Preview, out now - http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs (note that you can still use VS2015 even when targeting an older version of the .NET framework)

Dim multiline = "multi
line
string"

VB strings are basically now the same as C# verbatim strings - they don't support backslash escape sequences like \n, and they do allow newlines within the string, and you escape the quote symbol with double-quotes ""


this was a really helpful article for me, but nobody mentioned how to concatenate in case you want to send some variables, which is what you need to do 99% of the time.

... <%= variable %> ...

Here's how you do it:

<SQL> SELECT * FROM MyTable WHERE FirstName='<%= EnteredName %>' </SQL>.Value


Well, since you seem to be up on your python, may I suggest that you copy your text into python, like:

 s="""this is gonna 
last quite a 
few lines"""

then do a:

  for i in s.split('\n'):
    print 'mySB.AppendLine("%s")' % i

#    mySB.AppendLine("this is gonna")
#    mySB.AppendLine("last quite a")
#    mySB.AppendLine("few lines")

or

  print ' & _ \n'.join(map(lambda s: '"%s"' % s, s.split('\n')))

#    "this is gonna" & _ 
#    "last quite a" & _ 
#    "few lines"

then at least you can copy that out and put it in your VB code. Bonus points if you bind a hotkey (fastest to get with:Autohotkey) to do this for for whatever is in your paste buffer. The same idea works well for a SQL formatter.


Multi-line string literals in vb.net using the XElement class.

Imports System.Xml.Linq

Public Sub Test()

dim sOderBy as string = ""

dim xe as XElement = <SQL>
                SELECT * FROM <%= sTableName %>
                 <ORDER_BY> ORDER BY <%= sOrderBy %></ORDER_BY>
                 </SQL>

'** conditionally remove a section 
if sOrderBy.Length = 0 then xe.<ORDER BY>.Remove

'** convert XElement value to a string 
dim sSQL as String = xe.Value

End Sub

To me that is the most annoying thing about VB as a language. Seriously, i once wrote the string in a file and wrote code something along the lines of:

Dim s as String = file_get_contents("filename.txt")

just so i could test the query directly on SQL server if i need to.

My current method is to use a stored procedure on the SQL Server and just call that so i can pass in parameters to the query, etc


I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value

You could (should?) put the string in a resource-file (e.g. "My Project"/Resources) and then get it with

 Dim a = My.Resources.Whatever_you_chose

Disclaimer: I love python. It's multi-line strings are only one reason.

But I also do VB.Net, so here's my short-cut for more readable long strings.

  Dim lines As String() = {
    "Line 1",
    "Line 2",
    "Line 3"
  }
  Dim s As String = Join(lines, vbCrLf)

you can use XML for this like

dim vrstr as string = <s>
    some words
    some words
    some
    words
</s>

in Visual studio 2010 (VB NET)i try the following and works fine

Dim HtmlSample As String = <anything>what ever you want to type here with multiline strings</anything>

dim Test1 as string =<a>onother multiline example</a>

Available in Visual Basic 14 as part of Visual Studio 2015 https://msdn.microsoft.com/en-us/magazine/dn890368.aspx

But not yet supported by R#. The good news is they will be supported soon! Please vote on Youtrack to notify JetBrains you need them also.


If you need an XML literal in VB.Net with an line code variable, this is how you would do it:

<Tag><%= New XCData(T.Property) %></Tag>

You can also use System.Text.StringBuilder class in this way:

Dim sValue As New System.Text.StringBuilder
sValue.AppendLine("1st Line")
sValue.AppendLine("2nd Line")
sValue.AppendLine("3rd Line")

Then you get the multiline string using:

sValue.ToString()

Since this is a readability issue, I have used the following code:

MySql = ""
MySql = MySql & "SELECT myTable.id"
MySql = MySql & " FROM myTable"
MySql = MySql & " WHERE myTable.id_equipment = " & lblId.Text

Use vbCrLf or vbNewLine. It works with MessageBoxes and many other controls I tested.

Dim str As String
str = "First line" & vbCrLf & "Second line"
MsgBox(str)
str = "First line" & vbNewLine & "Second line"
MsgBox(str)

It will show two identical MessageBoxes with 2 lines.


No, VB.NET does not yet have such a feature. It will be available in the next iteration of VB (visual basic 10) however (link)


if it's like C# (I don't have VB.Net installed) you can prefix a string with @

foo = @"Multiline
String"

this is also useful for things like @"C:\Windows\System32\" - it essentially turns off escaping and turns on multiline.

참고URL : https://stackoverflow.com/questions/706382/multiline-strings-in-vb-net

반응형