pro*_*v42 72 c# language-agnostic glossary terminology
在文字字符串和文字值等上下文中使用时,"文字"这个词的含义是什么?
字面值和值之间有什么区别?
小智 110
文字是" 在源代码中表示值的任何符号"(维基百科)
(与此对比的标识符,这是指在存储器中的值.)
例子:
"hey" (一个字符串)false (布尔值)3.14 (实数)[1,2,3] (一个数字列表)(x) => x*x (一个功能)/^1?$|^(11+?)\1+$/ (正则表达式)一些不是文字的东西:
std::cout (标识符)foo = 0; (一份声明)1+2 (一种表达)Joe*_*orn 76
文字是一个直接硬编码到源中的值.
例如:
string x = "This is a literal";
int y = 2; // so is 2, but not y
int z = y + 4; // y and z are not literals, but 4 is
int a = 1 + 2; // 1 + 2 is not a literal (it is an expression), but 1 and 2 considered separately are literals
Run Code Online (Sandbox Code Playgroud)
一些文字可以有一个特殊的语法,所以你知道文字是什么类型:
//The 'M' in 10000000M means this is a decimal value, rather than int or double.
var accountBalance = 10000000M;
Run Code Online (Sandbox Code Playgroud)
使它们与变量或资源区别开来的是编译器可以将它们视为常量,或者使用使用它们的代码执行某些优化,因为它确定它们不会改变.
Ed *_* S. 15
文字是对显式值的赋值,例如
int i = 4; // i is assigned the literal value of '4'
int j = i // j is assigned the value of i. Since i is a variable,
//it can change and is not a 'literal'
Run Code Online (Sandbox Code Playgroud)
编辑:正如所指出的,赋值本身与文字的定义无关,我在我的例子中使用赋值,但文字也可以传递给方法等.
Mat*_*ley 11
文字是在源代码中包含值时(与引用变量或常量相反).例如:
int result = a + 5; // a is a variable with a value, 5 is a literal
string name = "Jeff Atwood"; // name is a variable initialized
// with the string literal, "Jeff Atwood"
int[] array = new int[] {1, 2, 3}; // C# has array literals (this is actually three
// int literals within an array literal)
Run Code Online (Sandbox Code Playgroud)
如果文字代表一些数量,比如物理常数,最好给它一个名字,而不是在你需要的任何地方写出相同的文字.这样,当您阅读源代码时,您就知道数字的含义,这通常比其值更重要(无论如何都可能会改变).
const int maxUsers = 100;
const double gravitationalAcceleration = 9.8;
Run Code Online (Sandbox Code Playgroud)
通常,我使用的唯一数字文字(除了像上面那样初始化常量)是0或1,如果我在循环中跳过每个其他项,有时为2.如果数字的含义比其实际值(通常是)更重要,那么更好地命名它.
文字值是一个值,但值也可以存储在变量中.在声明中
string str = "string literal";
Run Code Online (Sandbox Code Playgroud)
有一个字符串变量(str)和一个字符串文字.执行语句后,它们都具有相同的值.
请注意,在许多语言中,变量和文字值不一定必须是同一类型.例如:
int a = 1.0;
Run Code Online (Sandbox Code Playgroud)
上面的文字值是浮点类型.该值将由编译器强制进入int变量.
再举一个例子,在上面的第一行C++代码中,字符串文字的类型实际上根本不是库类型string.为了保持与C的向后兼容性,C++中的字符串文字是char数组.