基本操作符

. 成员访问操作符

  1. System.IO.File.Create("D:\\HelloWorld.txt");
  2. 1 2 3
  3. var myForm = new Form();
  4. myForm.Text = "Hello, World";
  5. 4
  6. myForm.ShowDialog();
  7. 4
  1. 访问外层名称空间中的子名称空间
  2. 访问名称空间中的类型
  3. 访问类型的静态成员
  4. 访问对象中的实例成员

f(x) 方法调用操作符

C# 里方法调用都要用到()
Action 是委托,委托在创建时只需要知道方法的名称,不调用方法,所以只会用到方法名(不加())。当然最终myAction();也用到了方法调用操作符()

  1. namespace OperatorsExample
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. Calculator c = new Calculator();
  8. double x = c.Add(3.0, 4.6);
  9. Console.WriteLine(x);
  10. Action myAction = new Action(c.PrintHello);//Action是委托,这里PrintHello没有加括号
  11. myAction();
  12. }
  13. }
  14. class Calculator
  15. {
  16. public double Add(double a,double b)
  17. {
  18. return a + b;
  19. }
  20. public void PrintHello()
  21. {
  22. Console.WriteLine("Hello");
  23. }
  24. }
  25. }

a[x] 元素访问操作符

访问数组元素:

  1. int[] myIntArray = new int[] { 1, 2, 3, 4, 5 };
  2. Console.WriteLine(myIntArray[0]);
  3. Console.WriteLine(myIntArray[myIntArray.Length - 1]);

索引字典中的元素

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Dictionary<string, Student> stuDic = new Dictionary<string, Student>();
  6. for (int i = 0; i < 100; i++)
  7. {
  8. Student stu = new Student()
  9. {
  10. Name = "s_" + i.ToString(),
  11. Score = 100 - i
  12. };
  13. stuDic.Add(stu.Name, stu);
  14. }
  15. Console.WriteLine(stuDic["s_6"].Score);
  16. }
  17. }
  18. class Student
  19. {
  20. public string Name;
  21. public int Score;
  22. }

x++ x-- 后置自增、自减操作符

先赋值,再自增。

  1. int x = 100;
  2. int y = x++;
  3. Console.WriteLine(x);
  4. Console.WriteLine(y);

7.2 各类操作符的示例 - 图1

typeof 操作符

检测类型元数据(Metadata)。

  1. // Metadata
  2. Type t = typeof(int);
  3. Console.WriteLine(t.Namespace);
  4. Console.WriteLine(t.FullName);
  5. Console.WriteLine(t.Name);
  6. int c = t.GetMethods().Length;
  7. Console.WriteLine(c);
  8. foreach (var m in t.GetMethods())
  9. {
  10. Console.WriteLine(m.Name);
  11. }

图片.png

default 操作符