转义代码段中的 $字符

最近我发现自己在做大量的 jQuery,所以我开始把一些常见的事情抽象成片段。我很期待与社区分享这些,但我现在遇到了一个问题。

代码片段中的文字是通过在文字的名称周围添加美元符号($)来定义的,以便分隔您希望提供的值的去向。这很困难,因为 jQuery 使用美元符号表示法来使用它的许多功能。

代码片段的转义序列是什么,这样我就可以使用美元符号,并且代码片段仍然可以正常工作?

21977 次浏览

To have a literal $ try doubling it: $$

Although the jQuery response is valid, it's a nicer syntax to use the $ notation.

I've found an answer: Making the $ character a literal with a default value of $.

<Literal Editable="true">


<ID>dollar</ID> <ToolTip>replace the dollar sign character</ToolTip> <Default>$</Default> <Function> </Function> </Literal>

There is an "Delimiter" attribute defined for a Code element. This defaults to $ but you can set it to a different character like ~ or so.

...

<Snippet>
<Code Language="JavaScript" Delimiter="~"><![CDATA[(function ($) {
$(document).ready(function () {


});
})(jQuery);]]></Code>
</Snippet>

...

I used this for a formattable string in C#. I used the example above from cory-fowler verbatim:

<Literal Editable="true">
<ID>dollar</ID>
<ToolTip>Replace the dollar sign character</ToolTip>
<Default>$</Default>
<Function></Function>
</Literal>

Usage (line breaks are added for clarity on Stack Overflow, not in the original.):

    string errMessage = $dollar$"Error occurred in
{MethodBase.GetCurrentMethod().Module}, in procedure
{MethodBase.GetCurrentMethod().Name}: {ex.Message}".ToString();

Thanks, cory-fowler!

This is the right way for Visual Studio Code: \\$.

This makes the $ a literal part of the snippet rather than the start of a $-prefixed construct.

I found the above cory-fowler answer useful, but was frustrated that the literal $ was pre-selected when executing a C# snippet in VS 2019...

Snippet with Literal Editable=true

It was also ignoring my $end$ keyword...

<![CDATA[string Literal_edit_true = $dollar$"$end$";]]>

Simply changing to Editable=false resolved the issue and now the cursor appears at $end$ ready to type...

Snippet with Literal Editable=false

<Snippet>
<Code Language="CSharp">
<![CDATA[string Literal_edit_false = $dollar$"$end$";]]>
</Code>
<Declarations>
<Literal Editable="false">
<ID>dollar</ID>
<ToolTip>Replace the dollar sign character</ToolTip>
<Default>$</Default>
<Function></Function>
</Literal>
</Declarations>
</Snippet>