由C#支持的还有其他一些重要的运算符,包括sizeof,typeof运算和? :。
运算符 | 描述 | 示例 |
---|---|---|
sizeof() | 返回一个数据类型的大小 | sizeof(int), 将返回 4. |
typeof() | 返回一个类的类型 | typeof(StreamReader); |
& | 返回一个变量的地址 | &a; 将给出变量的实际地址 |
* | 指针的变量 | *a; 将指向一个变量 |
? : | 条件表达式 | 如果条件为 true ? 那么为值 X : 否则为值 Y |
is | 判断一个对象是否是特定的类型 | If( Ford is Car) // checks if Ford is an object of the Car class. |
as | 转换,如果转换失败引发异常 |
Object obj = new StringReader("Hello"); StringReader r = obj as StringReader; |
例子
using System; namespace OperatorsAppl { class Program { static void Main(string[] args) { /* example of sizeof operator */ Console.WriteLine("The size of int is {0}", sizeof(int)); Console.WriteLine("The size of short is {0}", sizeof(short)); Console.WriteLine("The size of double is {0}", sizeof(double)); /* example of ternary operator */ int a, b; a = 10; b = (a == 1) ? 20 : 30; Console.WriteLine("Value of b is {0}", b); b = (a == 10) ? 20 : 30; Console.WriteLine("Value of b is {0}", b); Console.ReadLine(); } } }
让我们编译和运行上面的程序,这将产生以下结果:
The size of int is 4 The size of short is 2 The size of double is 8 Value of b is 30 Value of b is 20