2.3变量

var 类型推断

type 类的分类 如:type nametype = name.GetType(); //取变量name的类型

const 常量  const int painame = 3.1415

char 是字符类型 string是字符串类型

2.5语句

选择语句:switch(变量){case 常量值1:语句1 break;…………;default 常量值n:语句2 break;}

二个值相同语句时:switch(变量){case 常量值1:case 常量值1:语句1 break;…………;default 常量值n:语句2 break;}

wile 循环一般用在不知道循环多少次的情况下

do…wile 是先循环后判断

foreach() 遍历

goto 跳转语句 goto pray;语句1;…………;pray: 语句n; ///直接跳过语句1执行语句n (大多情况下不允许用慎用)

break 跳出循环体

continue 跳过当次循环(非跳出循环体)

2.6枚举型

  1. Main()
  2. {
  3. TimeOfDay time = (TimeOfDay)Enum.Parse(typeof(TimeOfDay), "afternoon",true); //从字符串对应的值,参数3区分大小写
  4. Console.WriteLine((int)time);
  5. TimeOfDay time2 = TimeOfDay.Evening;
  6. Console.WriteLine((int)time2);//输出为2
  1. }
  2. public enum TimeOfDay
  3. {
  4. morning = ,
  5. Afternoon = ,
  6. Evening = ,
  7. }

2.7空间名称

  1. testpray.testclass.Class1.***()
  2. namespace testpray
  3. {
  4. namespace testclass {
  5. class Class1
  6. {}}}

2.8给Main()方法传递参数

  1. static int Main(string[] args)
  2. {
  3. for (int i = ; i < args.Length; i++)
  4. {
  5. Console.WriteLine(args[i]);
  6. }
  7. return ;
  8. }
  9. //在CMD下运行程序 test /a /r /e ,a、r、e为参数

2.10控制台

Console.WriteLine("{0,4:C2}\n",i,} // 0表示索引值(对应变量I),4表示宽度(正直表示右对齐,负值表示左对齐,C2表输出精度后2位的货币,)

C 货币
D 十进制
E 科学计数法
F 小数点位数
G 普通格式 (只显示前n个有效数字)
N 显示千分制     12543.234      n2        12,543.12
p 百分数      0.52123           p2                 52.12%
X 十六进制    

2.12 C#预处理指令

#define  名称符号  (声明存在这个符号,用于调试)         #undef 名称符号 (删除符号)

#if  名称符号 (在前面的#define时才会执行)    #

3.3 类

类的参数,如果是引用类型(如数组或类)传递给方法,对应的方法会改变数组中的值,而新值会反射在原数组里.

ref 参数,在值参数前加入ref 其方法对参数的改变会在原始对象中体现!(调用时也要在参数上添加 ref)

out 参数,传递时变量可以不初始化,(调用时也要在参数前加 out)

命名参数,调用时可 test(i:32,98);

可选参数,必须在是方法定义的最后的参数(net4) 例:void test(int i,int n = 10) {…} //多个可选参数时可与命名参数指定参数!

方法的重载

属性的访问修饰符如: public name{get{} private set{}}

(构造函数???)

struct 定义一个结构体 如struct 名称 {}    注:结构是值类型

partial 部分类 ,在多个文件中存放有方法和属性  例: partial class name{}

3.10 扩展方法

扩展方法是静态方法  新建一个静态类,然后其内容中添加:

public static void AddToAmount(this 类名 参数1,扩展的方法) {参数1.Amount += 扩展的方法 }

4.3.1虚方法 (用于多态性)

virtual 关键字,例 基类: public virtual string Testprint(){} 派生类:public override string Testprint()注:字段与静态函数不能声明为virtual

  1. using System;
  2. namespace PolymorphismApplication
  3. {
  4. class Shape
  5. {
  6. protected int width, height;
  7. public Shape( int a=, int b=)
  8. {
  9. width = a;
  10. height = b;
  11. }
  12. public virtual int area()
  13. {
  14. Console.WriteLine("父类的面积:");
  15. return ;
  16. }
  17. }
  18. class Rectangle: Shape
  19. {
  20. public Rectangle( int a=, int b=): base(a, b)
  21. {
  22.  
  23. }
  24. public override int area ()
  25. {
  26. Console.WriteLine("Rectangle 类的面积:");
  27. return (width * height);
  28. }
  29. }
  30. class Triangle: Shape
  31. {
  32. public Triangle(int a = , int b = ): base(a, b)
  33. {
  34.  
  35. }
  36. public override int area()
  37. {
  38. Console.WriteLine("Triangle 类的面积:");
  39. return (width * height / );
  40. }
  41. }
  42. class Caller
  43. {
  44. public void CallArea(Shape sh)
  45. {
  46. int a;
  47. a = sh.area();
  48. Console.WriteLine("面积: {0}", a);
  49. }
  50. }
  51. class Tester
  52. {
  53.  
  54. static void Main(string[] args)
  55. {
  56. Caller c = new Caller();
  57. Rectangle r = new Rectangle(, );
  58. Triangle t = new Triangle(, );
  59. c.CallArea(r);
  60. c.CallArea(t);
  61. Console.ReadKey();
  62. }
  63. }
  64. }

实例:虚方法的多态性

4.3.2隐藏方法要隐藏基类时要用New

调用基类的方法 base.基类函数名()

抽象类与方法   必须在派生类中重写,   理解用于防漏写方法 修饰符:abstract

密封类与方法  例 sealed class name{} 对于类表示不能继承,  对于方法表示不能重写

注:应用于方法或属性时,sealed 修饰符必须始终与 override 结合使用。

4.36 带参数的构造函数  this()表示当前法

4.5 接口 关键字:interface   例  public interface IDisposable{} 有点类类似抽象类 接口的应用统一接口 相关介绍

派生的接口例:(如不理解请查看108页与相关介绍)

  1. public interface ITransferBankAccount : IBankAccount
  2. {
  3. bool TransferTo(IBankAccount destination, decimal amount);
  4. }

5.1.1泛型 相关介绍与用法可参考

5.3.2约束 where T :struct 对于结构约束,类型T必须是值类型

5.4.1 协变与抗变 相关资料 相关理解

  1. static void Main(string[] args)
  2. {
  3. //协变
  4. IIndex<Rectangle> rectangles = RectangleCollection.GetRectangles();
  5. IIndex<Shape> shapes = rectangles;
  6. for (var i = ; i < shapes.Count; i++)
  7. {
  8. Console.WriteLine(shapes[i]);
  9. }
  10. Console.ReadKey();
  11. }
  12. }
  13. public class Shape
  14. {
  15. public double Width { get; set; }
  16. public double Height { get; set; }
  17.  
  18. public override string ToString()
  19. {
  20. return string.Format("Width: {0}, Height: {1}.", Width.ToString(), Height.ToString());
  21. }
  22. }
  23. public class Rectangle : Shape
  24. {
  25.  
  26. }
  27.  
  28. public interface IIndex<out T>
  29. {
  30. T this[int index] { get; }
  31. int Count { get; }
  32. }
  33. public class RectangleCollection : IIndex<Rectangle>
  34. {
  35. private readonly Rectangle[] _data = new Rectangle[]
  36. {
  37. new Rectangle{Height = ,Width = },
  38. new Rectangle{Height = ,Width = },
  39. new Rectangle{Height = ,Width = },
  40. };
  41.  
  42. public static RectangleCollection GetRectangles()
  43. {
  44. return new RectangleCollection();
  45. }
  46.  
  47. public Rectangle this[int index]
  48. {
  49. get
  50. {
  51. if (index < || index > _data.Length)
  52. throw new ArgumentOutOfRangeException("index");
  53. return _data[index];
  54. }
  55. }
  56.  
  57. public int Count { get { return _data.Length; } }

协变实例

6.4锯齿数组

int[][] =new int[3],[]

6.5Array类 如果数组元素超出整数取值范围,可以做用longlength属性来获取元素大小,,,Rank属性-数组的维数

6.5.1创建数组 Array1.CreateInstance(typeof(int),5)

设置数组元素Array1.SetValue(元素值,下标); 获取元素Array1.GetValue(下标);

6.5.2复制数组 因数组为引用类型,所以不能直接用等号,如果数组的元素为值类型,复制用 Array2=(int[]) Array1.Clone(); 注意如果数组的元素为引用类型则只复制引用,修改其只一个会改变另一个对象,如要深层副本,则必须迭代数组并创建新对象。

6.5.3数组排序 简单类型int与String可直接Array.Sort(数组)排序,如自定义类, 要使之实现IComparable<类>接口的Compareto方法,如下:

  1. public int CompareTo(Person other)
  2. {
  3. if (other == null) throw new ArgumentNullException("other");
  4.  
  5. int result = this.LastName.CompareTo(other.LastName);
  6. if (result == )
  7. {
  8. result = this.FirstName.CompareTo(other.FirstName);
  9. }
  10.  
  11. return result;
  12. }

6.6.2 ArraySegment<T>

  1. static void Main()
  2. {
  3. int[] ar1 = { , , , , , };
  4. int[] ar2 = { , , , , , , };
  5. //分隔ar1的索引0后的3个元素,与ar2的索引3后的3个元素.
  6. var segments = new ArraySegment<int>[] {new ArraySegment<int>(ar1, , ), new ArraySegment<int>(ar2, , )};
  7. var sum = SumOfSegments(segments);
  8. Console.WriteLine("sum of all segments: {0}", sum);
  9. Console.ReadKey();
  10. }
  11.  
  12. static int SumOfSegments(ArraySegment<int>[] segments)
  13. {
  14. int sum = ;
  15. foreach (var segment in segments)
  16. {
  17. for (int i = segment.Offset; i < segment.Offset + segment.Count; i++)
  18. //i取的是数组的原数组下标值!即ar1与ar2的下标
  19. {
  20. sum += segment.Array[i];
  21. }
  22. }
  23. return sum;
  24. }

如数组段中改变了数组,则原数组也会改变!

6.7.3yield语句(yield是一个语法糖)

1迭代集合不同方式

  1. class Program
  2. {
  3. static void Main()
  4. {
  5. var titles = new MusicTitles();
  6. foreach (var title in titles.Subset(, ))
  7. {
  8. Console.WriteLine(title);
  9. }
  10. }
  11. }
  12. public class MusicTitles
  13. {
  14. string[] names = { "Tubular Bells", "Hergest Ridge", "Ommadawn", "Platinum" };
  15. public IEnumerable<string> Subset(int index, int length)
  16. {
  17. for (int i = index; i < index + length;
  18. i++)
  19. {
  20. yield return names[i];
  21. }
  22. }
  23. }

2用yieid return 返回枚举器

  1. static void Main()
  2. {
  3. var game = new GameMoves();
  4. IEnumerator enumerator = game.Cross();
  5. while (enumerator.MoveNext())
  6. {
  7. enumerator = enumerator.Current as IEnumerator;
  8. }
  9. Console.ReadLine();
  10. }
  11.  
  12. public class GameMoves
  13. {
  14. private IEnumerator cross;
  15. private IEnumerator circle;
  16. public GameMoves()
  17. {
  18. cross = Cross();
  19. circle = Circle();
  20. }
  21. private int move = ;
  22. const int MaxMoves = ;
  23. public IEnumerator Cross()
  24. {
  25. while (true)
  26. {
  27. Console.WriteLine("Cross, move {0}", move);
  28. if (++move >= MaxMoves)
  29. yield break;
  30. yield return circle;//下一次为circle方法
  31. }
  32. }
  33. public IEnumerator Circle()
  34. {
  35. while (true)
  36. {
  37. Console.WriteLine("Circle, move {0}", move);
  38. if (++move >= MaxMoves)
  39. yield break;
  40. yield return cross;//下一次为Cross方法
  41. }
  42. }
  43. }

6.8元组

  1. var result = Divide(, );
  2. Console.WriteLine("result of division: {0}, reminder: {1}, resum:{2}", result.Item1, result.Item2, result.Item3);
  3. public static Tuple<int, int,int> Divide(int dividend, int divisor)
  4. {
  5. int result = dividend / divisor;
  6. int reminder = dividend % divisor;
  7. int resum = dividend + divisor;
  8. return Tuple.Create<int,int,int>(result, reminder, resum);

6.9结构比较

通过类IStructuralEquatable接口实现比较内容与引用!

对于IstructuralEquatable接口定义的Equals()方法,它的第一个参数是object类型,
       第二个参数是IEqualityComparer类型。调用这个方法时,通过传递一个实现了IEqualityComparer<T>的对象,就
      可以定义如何进行比较。通过EqualityComparer<T>类完成IEqualityComparer的一个默认实现。这个实现检查类型是否
      实现了IEquatable接口,并调用IEquatable.Equals()方法(即这里的Person类的Equals方法)。如果该类型没有实现IEquatable,就
      调用Object基类中的Equals()方法进行比较。
                  if ((persons1 as IStructuralEquatable).Equals(
                persons2, EqualityComparer<Person>.Default))
       单步调试上面这行代码时,由于persons1和persons2共有三个元素
       所以比较函数会进行三次(注意:会被执行三次),由于两个数组中第三个元素的FirstName
       不相同,所以返回内容不相同的结果
注意:如果两个数组的元素个数不相等,则直接返回不相等,不会调用Person类的Equals比较方法

  1. static void Main()
  2. {
  3. var janet = new Person { FirstName = "Janet", LastName = "Jackson"};
  4. Person[] persons1 = { new Person { FirstName = "Michael", LastName = "Jackson" }, janet };
  5. Person[] persons2 = { new Person { FirstName = "Michae2", LastName = "Jackson" }, janet };
  6. Console.WriteLine(janet.ToString());
  7. Console.ReadLine();
  8. if (persons1 != persons2) {
  9. Console.WriteLine("不相同的引用");
  10. }
  11. if (!persons1.Equals(persons2))
  12. Console.WriteLine("等于返回false -不相同的引用");
  13. if ((persons1 as IStructuralEquatable).Equals(persons2, EqualityComparer<Person>.Default))
  14. Console.WriteLine("相同的内容");
  15. }
  16.  
  17. public class Person : IEquatable<Person>
  18. {
  19. public int Id { get; private set; }
  20. public string FirstName { get; set; }
  21. public string LastName { get; set; }
  22.  
  23. public override string ToString()
  24. {
  25. return String.Format("{0}, {1} {2}", Id, FirstName, LastName);
  26. }
  27. public bool Equals(Person other)
  28. {
  29. if (other == null)
  30. return base.Equals(other);
  31.  
  32. return this.FirstName == other.FirstName && this.LastName == other.LastName;
  33. }
  34. }

C#高级编程笔记 (1至6章节)数组,类/方法/泛型的更多相关文章

  1. C#高级编程笔记 (6至10章节)运算符/委托/字符/正则/集合

    数学的复习,4^-2即是1/4/4的意思, 4^2是1*2*2的意思,而10^-2为0.01! 7.2运算符 符号 说明 例   ++ 操作数加1 int i=3; j=i++; 运算后i的值为4,j ...

  2. C#高级编程笔记(22至25章节)文件\注册表\权限\事务

    22安全(using System.Security.Principal;) AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.Wi ...

  3. C#高级编程笔记(17至21章节)线程/任务

    17 Visual Studio 2013 控制台用Ctrl+F5可以显示窗口,不用加Console.ReadLine(); F5用于断点调式 程式应该使用发布,因为发布的程序在发布时会进行优化, 2 ...

  4. Android高级编程笔记(四)深入探讨Activity(转)

    在应用程序中至少包含一个用来处理应用程序的主UI功能的主界面屏幕.这个主界面一般由多个Fragment组成,并由一组次要Activity支持.要在屏幕之间切换,就必须要启动一个新的Activity.一 ...

  5. UNIX环境高级编程笔记之文件I/O

    一.总结 在写之前,先唠几句,<UNIX环境高级编程>,简称APUE,这本书简直是本神书,像我这种小白,基本上每看完一章都是“哇”这种很吃惊的表情.其实大概三年前,那会大三,我就买了这本书 ...

  6. javascript高级编程笔记01(基本概念)

    1.在html中使用JavaScript 1.  <script> 元素 <script>定义了下列6个属性: async:可选,异步下载外部脚本文件. charset:可选, ...

  7. C#高级编程笔记之第三章:对象和类型

    类和结构的区别 类成员 匿名类型 结构 弱引用 部分类 Object类,其他类都从该类派生而来 扩展方法 3.2 类和结构 类与结构的区别是它们在内存中的存储方式.访问方式(类似存储在堆上的引用类型, ...

  8. C#高级编程笔记之第二章:核心C#

    变量的初始化和作用域 C#的预定义数据类型 流控制 枚举 名称空间 预处理命令 C#编程的推荐规则和约定 变量的初始化和作用域 初始化 C#有两个方法可以一确保变量在使用前进行了初始化: 变量是字段, ...

  9. C#高级编程笔记(11至16章)异步/托管/反射/异常

    11.1.2LINQ语句 LINQ查询表达式以from子句开始,以select或者group子句结束.在这两个子句之间可以跟零个或者多个from.let.where.join或者orderby子句. ...

随机推荐

  1. 【CF1243B1】Character Swap (Easy Version)【思维】

    题意:给你两个字符串,问是否存在交换方案使得两个字符串变成一样的,方案为只交换一次且只交换s1与s2里的一个字符 题解:若一开始就相同,则存在交换方案 若一开始不同的位置为1个或大于2个,则不存在方案 ...

  2. vim 批量添加删除注释

    vim中单行注释只是多行注释的一个特例,这里统一进行多行注释的讲解 (1)添加批量注释 ctrl+v 进入列编辑模式,向下或向上移动光标,把需要注释的行的开头标记起来,然后按大写的I(shift+i) ...

  3. linux如何查看端口被哪个进程占用的方法

    linux如何查看端口被哪个进程占用的方法: 1.lsof -i:端口号2.netstat -tunlp|grep 端口号 都可以查看指定端口被哪个进程占用的情况[步骤一]lsof -ilsof -i ...

  4. leetcode 235. 二叉搜索树的最近公共祖先(c++)

    给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先. 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p.q,最近公共祖先表示为一个结点 x,满足 x 是 p.q 的祖先且 x ...

  5. Nginx 实现全站 HTTPS(基于 Let's Encrypt 的免费通配符证书)

    单域名证书的生成可以 参考这里. acme.sh 项目中文文档 Let's Encrypt 在 18 年 1 月份推出了 ACME v2,支持通配符域名证书,对小网站.个人站长的友好度进一步增加. 常 ...

  6. oracle两表中的两列进行模糊匹配的方法

    SELECT T2.列名,T1.列名  FROM 主表 T1, 匹配表 T2    WHERE  T1.匹配列  LIKE CONCAT('%',concat(T2.匹配列,'%')); 注意:  a ...

  7. java文件上传下载 使用SmartUpload组件实现

    使用SmartUpload组件实现(下载jsmartcom_zh_CN.jar) 2017-11-07 1.在WebRoot创建以下文件夹,css存放样式文件(css文件直接拷贝进去),images存 ...

  8. Throwable -抛出异常类与自定义异常类

    /* 自定义异常类 java提供的异常类,不够我们使用,需要自己定义一些异常类 格式: public class XXXException extends Exception/runtimeExcep ...

  9. Spring Security 04

    转至:Elim的博客http://elim.iteye.com/blog/2161648 Filter Porxy DelegatingFilterProxy DelegationFilterProx ...

  10. [Linux] 026 光盘 yum 源搭建

    光盘 yum 搭建步骤 (1) 挂载光盘 $ mount /dev/cdrom /mnt/cdrom/ (2) 让网络 yum 源文件失效 $ cd /etc/yum.repos.d/ $ mv Ce ...