1. C# 的各种操作符
C# Operators
2. 操作符举例
- type 与 typeof
Type t = typeof(int);
Console.WriteLine(t);
Console.WriteLine(t.Namespace);// 得到 int 类型的命名空间
Console.WriteLine(t.GetMethods().Length);
foreach (var item in t.GetMethods())
{
Console.WriteLine(item);
}
- var 与 new
// var可以声明隐式类型变量,用于指向 new 操作符声明的匿名类型对象。
var person = new { Name = "Mr.Li", Age = 34 };
Console.WriteLine(person.Name);
Console.WriteLine(person.Age);
- checked 与 unchecked
// 用于判断一个变量的数值是不是在内存中有溢出
try
{
uint x = uint.MaxValue;
uint y = checked(x + 1);// 显然,有溢出,抛出OverflowException
Console.WriteLine(y);
}
catch (OverflowException)
{
Console.WriteLine("There is an overflow");
}
-
隐式类型转换和强制类型转换
类型转换 - is 与 as
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Teacher teacher = new Teacher();
Human Liming = teacher;
// is 用来判断类型,返回布尔值
if(Liming is Teacher)
{
Console.WriteLine("Liming is a teacher");
}
Human Wangping = new Teacher();
// as 用来判断类型,若 Wangping 是 Teacher 类型,则赋值给变量 t,
// 若 Wangping 是 Teacher 类型,则变量 t 为 null。
Teacher t = Wangping as Teacher;
if (t != null)
{
Console.WriteLine("Wangping is a teacher!");
}
}
}
class Human
{
public void Eat()
{
Console.WriteLine("I eat an apple!");
}
}
class Teacher : Human
{
public void Teach()
{
Console.WriteLine("I teach C#.");
}
}
}
- ? 与 ??
① 可空类型操作符
引用类型可以使用空引用表示一个不存在的值,而值类型通常不能表示为空。例如:string str=null; 是正确的,int i=null; 编译器就会报错。为了使值类型也可为空,就可以使用可空类型,即用可空类型修饰符"?“来表示,表现形式为"T?”例如:int? 表示可空的整形,DateTime? 表示可为空的时间。T? 其实是System.Nullable(泛型结构)的缩写形式,也就意味着当你用到T?时编译器编译时会把T?编译成System.Nullable的形式。例如:int?,编译后便是System.Nullable的形式。
② 空合并运算符
用于定义可空类型和引用类型的默认值。如果此运算符的左操作数不为null,则此运算符将返回左操作数,否则返回右操作数。例如:a??b 当a为null时则返回b,a不为null时则返回a本身。空合并运算符为右结合运算符,即操作时从右向左进行组合的。如,“a??b??c”的形式按“a??(b??c)”计算。