C#代码中的美元符号是什么意思? [英] What do dollar symbols in C# Code mean?

查看:254
本文介绍了C#代码中的美元符号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我从客户端提取代码,并且在此行中遇到错误.

Today, I pull the code from my client, and I get an error in this line.

throw new Exception($"One or more errors occurred during removal of the company:{Environment.NewLine}{Environment.NewLine}{exc.Message}");

此行也

moreCompanies = $"{moreCompanies},{databaseName}";

$符号对我来说太奇怪了.这是C#代码.

The $ symbols is so weird with me. This is C# code.

推荐答案

$ 部分告诉编译器您需要插值字符串是的新功能之一C#6.0 .它们允许您用相应的值替换字符串文字中的占位符.

Interpolated strings are one of the new features of C# 6.0. They allow you to substitute placeholders in a string literal with their corresponding values.

您几乎可以将任何表达式放在插值字符串内的一对大括号( {} )之间,并且该表达式将替换为该表达式结果的 ToString 表示形式

You can put almost any expression between a pair of braces ({}) inside an interpolated string and that expression will be substituted with the ToString representation of that expression's result.

当编译器遇到插值字符串时,它将立即将其转换为对 String.Format 函数的调用.正因为如此,您的第一个清单基本上与写作相同:

When the compiler encounters an interpolated string, it immediately converts it into a call to the String.Format function. It is because of this that your first listing is essentially the same as writing:

throw new Exception(string.Format(
    "One or more errors occured during removal of the company:{0}{1}{2}", 
    Envrionment.NewLine, 
    Environment.NewLine, 
    exc.Message));

如您所见,插值字符串使您能够以更简洁的方式和更容易获得正确的方式来表达相同的事物.

As you can see, interpolated strings allow you to express the same thing in a much more succinct manner and in a way that is easier to get correct.

这篇关于C#代码中的美元符号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆