先决条件:字符串插值和逐字字符串
在C#8.0之前,您可以按特定顺序一起使用字符串插值($)和逐字标识符(@)。这意味着当同时使用$令牌和@令牌时,必须$令牌必须出现在@令牌之前。如果在$令牌之前使用@令牌,则编译器将给您一个错误,如以下示例所示:
范例1:
// C# program to illustrate the use
// of interpolated verbatim strings
using System;
class GFG {
// Main Method
static void Main()
{
int Base = 10;
int Height = 30;
int area = (Base * Height) / 2;
// Here, $ token appears before @ token
Console.WriteLine("Finding the area of a triangle:");
Console.WriteLine($@"Height = ""{Height}"" and Base = ""{Base}""");
Console.WriteLine($@"Area = ""{area}""");
}
}
输出:
Finding the area of a triangle:
Height = "30" and Base = "10"
Area = "150"
范例2:
// C# program to illustrate the use
// of interpolated verbatim strings
using System;
class GFG {
// Main Method
static void Main()
{
int Base = 10;
int Height = 30;
int area = (Base * Height) / 2;
// Here, @ token appears before $ token
// But the compiler will give an error
Console.WriteLine("Finding the area of a triangle:");
Console.WriteLine(@ $"Height = ""{Height}"" and Base = ""{Base}""");
Console.WriteLine(@ $"Area = ""{area}""");
}
}
错误:
error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
error CS1646: Keyword, identifier, or string expected after verbatim specifier: @
当我们在$令牌之前使用@令牌时,编译器将给出错误。此问题在C#8.0中已解决,现在允许您在$令牌之前使用@令牌,或者在$令牌之前使用$令牌
$@"..."
Or
@$"..."
并且编译器不会给出错误。如下例所示:
例子:
// C# program to illustrate the use
// of interpolated verbatim strings
using System;
namespace Geeks {
class GFG {
// Main Method
static void Main(string[] args)
{
int Base = 40;
int Height = 80;
int area = (Base * Height) / 2;
Console.WriteLine("Finding the area of a triangle:");
// Here, $ token appears before @ token
Console.WriteLine($@"Height = ""{Height}"" and Base = ""{Base}""");
// Here, @ token appears before $ token
Console.WriteLine(@$"Area = ""{area}""");
}
}
}
输出:
Finding the area of a triangle:
Height = "80" and Base = "40"
Area = "1600"