1.大写String和小写string区别是什么?
Net中定义了通用的数据类型(CTS,Common Type System):String、Int16、Int32、Int64、Boolean、Double。通过转到定义可以看到这些都是类(结构体)。C#语言规范中定义了string、int、long、bool、double等原始类型,编译器会把这些类型翻译成CTS中的类。反编译看IL就能看到了。
2.三元运算符
语法, 条件表达式?表达式1:表达式2;
如果条件表达式为true,则表达式的值为表达式1,否则为表达式2.
string str = null;
bool flag = false;
if(flag)
{
<span style="white-space:pre"> </span>str = "正确";
}
else
{
<span style="white-space:pre"> </span>str = "错误";
}
等价于:
string str = null;
bool flag = false;
str = flag ? "正确" : "错误";
3.文艺的??操作符
来自MSDN的描述:可以为 null 的类型可以表示类型的域中的值,或者值可以是未定义的(在这种情况下,值为 null)。 当左操作数具有一个值为 null 的可以为 null 的类型时,可以使用 ?? 运算符的语法表现力来返回适当的值(右操作数)。 如果在尝试将可以为 null 值的类型分配给不可以为 null 值的类型时没有使用 ?? 运算符,则会生成编译时错误。 如果使用强制转换,且当前未定义可以为 null 值的类型,则会引发 InvalidOperationException 异常。
class NullCoalesce
{
static int? GetNullableInt()
{
return null;
}
static string GetStringValue()
{
return null;
}
static void Main()
{
int? x = null;
// Set y to the value of x if x is NOT null; otherwise,
// if x = null, set y to -1.
int y = x ?? -1;
// Assign i to return value of the method if the method's result
// is NOT null; otherwise, if the result is null, set i to the
// default value of int.
int i = GetNullableInt() ?? default(int);
string s = GetStringValue();
// Display the value of s if s is NOT null; otherwise,
// display the string "Unspecified".
Console.WriteLine(s ?? "Unspecified");
}
}