加载中...

C#


其中 Y=c

源代码下载: LearnCSharp-cn.cs

C#是一个优雅的、类型安全的面向对象语言。使用C#,开发者可以在.NET框架下构建安全、健壮的应用程序。

更多关于C#的介绍

  1. // 单行注释以 // 开始
  2. /*
  3. 多行注释是这样的
  4. */
  5. /// <summary>
  6. /// XML文档注释
  7. /// </summary>
  8. // 声明应用用到的命名空间
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Data.Entity;
  12. using System.Dynamic;
  13. using System.Linq;
  14. using System.Linq.Expressions;
  15. using System.Net;
  16. using System.Threading.Tasks;
  17. using System.IO;
  18. // 定义作用域,将代码组织成包
  19. namespace Learning
  20. {
  21. // 每个 .cs 文件至少需要包含一个和文件名相同的类
  22. // 你可以不这么干,但是这样不好。
  23. public class LearnCSharp
  24. {
  25. // 基本语法 - 如果你以前用过 Java 或 C++ 的话,可以直接跳到后文「有趣的特性」
  26. public static void Syntax()
  27. {
  28. // 使用 Console.WriteLine 打印信息
  29. Console.WriteLine("Hello World");
  30. Console.WriteLine(
  31. "Integer: " + 10 +
  32. " Double: " + 3.14 +
  33. " Boolean: " + true);
  34. // 使用 Console.Write 打印,不带换行符号
  35. Console.Write("Hello ");
  36. Console.Write("World");
  37. ///////////////////////////////////////////////////
  38. // 类型和变量
  39. //
  40. // 使用 <type> <name> 定义变量
  41. ///////////////////////////////////////////////////
  42. // Sbyte - 有符号 8-bit 整数
  43. // (-128 <= sbyte <= 127)
  44. sbyte fooSbyte = 100;
  45. // Byte - 无符号 8-bit 整数
  46. // (0 <= byte <= 255)
  47. byte fooByte = 100;
  48. // Short - 16-bit 整数
  49. // 有符号 - (-32,768 <= short <= 32,767)
  50. // 无符号 - (0 <= ushort <= 65,535)
  51. short fooShort = 10000;
  52. ushort fooUshort = 10000;
  53. // Integer - 32-bit 整数
  54. int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647)
  55. uint fooUint = 1; // (0 <= uint <= 4,294,967,295)
  56. // Long - 64-bit 整数
  57. long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
  58. ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615)
  59. // 数字默认为 int 或 uint (取决于尺寸)
  60. // 使用 L 标明变量值类型为long 或 ulong
  61. // Double - 双精度 64-bit IEEE 754 浮点数
  62. double fooDouble = 123.4; // 精度: 15-16 位
  63. // Float - 单精度 32-bit IEEE 754 浮点数
  64. float fooFloat = 234.5f; // 精度: 7 位
  65. // 使用 f 标明变量值类型为float
  66. // Decimal - 128-bits 数据类型,比其他浮点类型精度更高
  67. // 适合财务、金融
  68. decimal fooDecimal = 150.3m;
  69. // 布尔值 - true & false
  70. bool fooBoolean = true; // 或 false
  71. // Char - 单个 16-bit Unicode 字符
  72. char fooChar = 'A';
  73. // 字符串 -- 和前面的基本类型不同,字符串不是值,而是引用。
  74. // 这意味着你可以将字符串设为null。
  75. string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)";
  76. Console.WriteLine(fooString);
  77. // 你可以通过索引访问字符串的每个字符:
  78. char charFromString = fooString[1]; // => 'e'
  79. // 字符串不可修改: fooString[1] = 'X' 是行不通的;
  80. // 根据当前的locale设定比较字符串,大小写不敏感
  81. string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
  82. // 基于sprintf的字符串格式化
  83. string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2);
  84. // 日期和格式
  85. DateTime fooDate = DateTime.Now;
  86. Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
  87. // 使用 @ 符号可以创建跨行的字符串。使用 "" 来表示 "
  88. string bazString = @"Here's some stuff
  89. on a new line! ""Wow!"", the masses cried";
  90. // 使用const或read-only定义常量
  91. // 常量在编译期演算
  92. const int HOURS_I_WORK_PER_WEEK = 9001;
  93. ///////////////////////////////////////////////////
  94. // 数据结构
  95. ///////////////////////////////////////////////////
  96. // 数组 - 从0开始计数
  97. // 声明数组时需要确定数组长度
  98. // 声明数组的格式如下:
  99. // <datatype>[] <var name> = new <datatype>[<array size>];
  100. int[] intArray = new int[10];
  101. // 声明并初始化数组的其他方式:
  102. int[] y = { 9000, 1000, 1337 };
  103. // 访问数组的元素
  104. Console.WriteLine("intArray @ 0: " + intArray[0]);
  105. // 数组可以修改
  106. intArray[1] = 1;
  107. // 列表
  108. // 列表比数组更常用,因为列表更灵活。
  109. // 声明列表的格式如下:
  110. // List<datatype> <var name> = new List<datatype>();
  111. List<int> intList = new List<int>();
  112. List<string> stringList = new List<string>();
  113. List<int> z = new List<int> { 9000, 1000, 1337 }; // i
  114. // <>用于泛型 - 参考下文
  115. // 列表无默认值
  116. // 访问列表元素时必须首先添加元素
  117. intList.Add(1);
  118. Console.WriteLine("intList @ 0: " + intList[0]);
  119. // 其他数据结构:
  120. // 堆栈/队列
  121. // 字典 (哈希表的实现)
  122. // 哈希集合
  123. // 只读集合
  124. // 元组 (.Net 4+)
  125. ///////////////////////////////////////
  126. // 操作符
  127. ///////////////////////////////////////
  128. Console.WriteLine("\n->Operators");
  129. int i1 = 1, i2 = 2; // 多重声明的简写形式
  130. // 算术直截了当
  131. Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3
  132. // 取余
  133. Console.WriteLine("11%3 = " + (11 % 3)); // => 2
  134. // 比较操作符
  135. Console.WriteLine("3 == 2? " + (3 == 2)); // => false
  136. Console.WriteLine("3 != 2? " + (3 != 2)); // => true
  137. Console.WriteLine("3 > 2? " + (3 > 2)); // => true
  138. Console.WriteLine("3 < 2? " + (3 < 2)); // => false
  139. Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true
  140. Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true
  141. // 位操作符
  142. /*
  143. ~ 取反
  144. << 左移(有符号)
  145. >> 右移(有符号)
  146. & 与
  147. ^ 异或
  148. | 或
  149. */
  150. // 自增、自减
  151. int i = 0;
  152. Console.WriteLine("\n->Inc/Dec-rementation");
  153. Console.WriteLine(i++); //i = 1\. 事后自增
  154. Console.WriteLine(++i); //i = 2\. 事先自增
  155. Console.WriteLine(i--); //i = 1\. 事后自减
  156. Console.WriteLine(--i); //i = 0\. 事先自减
  157. ///////////////////////////////////////
  158. // 控制结构
  159. ///////////////////////////////////////
  160. Console.WriteLine("\n->Control Structures");
  161. // 类似C的if语句
  162. int j = 10;
  163. if (j == 10)
  164. {
  165. Console.WriteLine("I get printed");
  166. }
  167. else if (j > 10)
  168. {
  169. Console.WriteLine("I don't");
  170. }
  171. else
  172. {
  173. Console.WriteLine("I also don't");
  174. }
  175. // 三元表达式
  176. // 简单的 if/else 语句可以写成:
  177. // <条件> ? <真> : <假>
  178. string isTrue = (true) ? "True" : "False";
  179. // While 循环
  180. int fooWhile = 0;
  181. while (fooWhile < 100)
  182. {
  183. //迭代 100 次, fooWhile 0->99
  184. fooWhile++;
  185. }
  186. // Do While 循环
  187. int fooDoWhile = 0;
  188. do
  189. {
  190. //迭代 100 次, fooDoWhile 0->99
  191. fooDoWhile++;
  192. } while (fooDoWhile < 100);
  193. //for 循环结构 => for(<初始条件>; <条件>; <步>)
  194. for (int fooFor = 0; fooFor < 10; fooFor++)
  195. {
  196. //迭代10次, fooFor 0->9
  197. }
  198. // foreach循环
  199. // foreach 循环结构 => foreach(<迭代器类型> <迭代器> in <可枚举结构>)
  200. // foreach 循环适用于任何实现了 IEnumerable 或 IEnumerable<T> 的对象。
  201. // .Net 框架下的集合类型(数组, 列表, 字典...)
  202. // 都实现了这些接口
  203. // (下面的代码中,ToCharArray()可以删除,因为字符串同样实现了IEnumerable)
  204. foreach (char character in "Hello World".ToCharArray())
  205. {
  206. //迭代字符串中的所有字符
  207. }
  208. // Switch 语句
  209. // switch 适用于 byte、short、char和int 数据类型。
  210. // 同样适用于可枚举的类型
  211. // 包括字符串类, 以及一些封装了原始值的类:
  212. // Character、Byte、Short和Integer。
  213. int month = 3;
  214. string monthString;
  215. switch (month)
  216. {
  217. case 1:
  218. monthString = "January";
  219. break;
  220. case 2:
  221. monthString = "February";
  222. break;
  223. case 3:
  224. monthString = "March";
  225. break;
  226. // 你可以一次匹配多个case语句
  227. // 但是你在添加case语句后需要使用break
  228. // (否则你需要显式地使用goto case x语句)
  229. case 6:
  230. case 7:
  231. case 8:
  232. monthString = "Summer time!!";
  233. break;
  234. default:
  235. monthString = "Some other month";
  236. break;
  237. }
  238. ///////////////////////////////////////
  239. // 转换、指定数据类型
  240. ///////////////////////////////////////
  241. // 转换类型
  242. // 转换字符串为整数
  243. // 转换失败会抛出异常
  244. int.Parse("123");//返回整数类型的"123"
  245. // TryParse会尝试转换类型,失败时会返回缺省类型
  246. // 例如 0
  247. int tryInt;
  248. if (int.TryParse("123", out tryInt)) // Funciton is boolean
  249. Console.WriteLine(tryInt); // 123
  250. // 转换整数为字符串
  251. // Convert类提供了一系列便利转换的方法
  252. Convert.ToString(123);
  253. // or
  254. tryInt.ToString();
  255. }
  256. ///////////////////////////////////////
  257. // 类
  258. ///////////////////////////////////////
  259. public static void Classes()
  260. {
  261. // 参看文件尾部的对象声明
  262. // 使用new初始化对象
  263. Bicycle trek = new Bicycle();
  264. // 调用对象的方法
  265. trek.SpeedUp(3); // 你应该一直使用setter和getter方法
  266. trek.Cadence = 100;
  267. // 查看对象的信息.
  268. Console.WriteLine("trek info: " + trek.Info());
  269. // 实例化一个新的Penny Farthing
  270. PennyFarthing funbike = new PennyFarthing(1, 10);
  271. Console.WriteLine("funbike info: " + funbike.Info());
  272. Console.Read();
  273. } // 结束main方法
  274. // 终端程序 终端程序必须有一个main方法作为入口
  275. public static void Main(string[] args)
  276. {
  277. OtherInterestingFeatures();
  278. }
  279. //
  280. // 有趣的特性
  281. //
  282. // 默认方法签名
  283. public // 可见性
  284. static // 允许直接调用类,无需先创建实例
  285. int, //返回值
  286. MethodSignatures(
  287. int maxCount, // 第一个变量,类型为整型
  288. int count = 0, // 如果没有传入值,则缺省值为0
  289. int another = 3,
  290. params string[] otherParams // 捕获其他参数
  291. )
  292. {
  293. return -1;
  294. }
  295. // 方法可以重名,只要签名不一样
  296. public static void MethodSignature(string maxCount)
  297. {
  298. }
  299. //泛型
  300. // TKey和TValue类由用用户调用函数时指定。
  301. // 以下函数模拟了Python的SetDefault
  302. public static TValue SetDefault<TKey, TValue>(
  303. IDictionary<TKey, TValue> dictionary,
  304. TKey key,
  305. TValue defaultItem)
  306. {
  307. TValue result;
  308. if (!dictionary.TryGetValue(key, out result))
  309. return dictionary[key] = defaultItem;
  310. return result;
  311. }
  312. // 你可以限定传入值的范围
  313. public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
  314. {
  315. // 我们可以进行迭代,因为T是可枚举的
  316. foreach (var item in toPrint)
  317. // ittm为整数
  318. Console.WriteLine(item.ToString());
  319. }
  320. public static void OtherInterestingFeatures()
  321. {
  322. // 可选参数
  323. MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
  324. MethodSignatures(3, another: 3); // 显式指定参数,忽略可选参数
  325. // 扩展方法
  326. int i = 3;
  327. i.Print(); // 参见下面的定义
  328. // 可为null的类型 对数据库交互、返回值很有用
  329. // 任何值类型 (i.e. 不为类) 添加后缀 ? 后会变为可为null的值
  330. // <类型>? <变量名> = <值>
  331. int? nullable = null; // Nullable<int> 的简写形式
  332. Console.WriteLine("Nullable variable: " + nullable);
  333. bool hasValue = nullable.HasValue; // 不为null时返回真
  334. // ?? 是用于指定默认值的语法糖
  335. // 以防变量为null的情况
  336. int notNullable = nullable ?? 0; // 0
  337. // 变量类型推断 - 你可以让编译器推断变量类型:
  338. var magic = "编译器确定magic是一个字符串,所以仍然是类型安全的";
  339. // magic = 9; // 不工作,因为magic是字符串,而不是整数。
  340. // 泛型
  341. //
  342. var phonebook = new Dictionary<string, string>() {
  343. {"Sarah", "212 555 5555"} // 在电话簿中加入新条目
  344. };
  345. // 调用上面定义为泛型的SETDEFAULT
  346. Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // 没有电话
  347. // 你不用指定TKey、TValue,因为它们会被隐式地推导出来
  348. Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555
  349. // lambda表达式 - 允许你用一行代码搞定函数
  350. Func<int, int> square = (x) => x * x; // 最后一项为返回值
  351. Console.WriteLine(square(3)); // 9
  352. // 可抛弃的资源管理 - 让你很容易地处理未管理的资源
  353. // 大多数访问未管理资源 (文件操作符、设备上下文, etc.)的对象
  354. // 都实现了IDisposable接口。
  355. // using语句会为你清理IDisposable对象。
  356. using (StreamWriter writer = new StreamWriter("log.txt"))
  357. {
  358. writer.WriteLine("这里没有什么可疑的东西");
  359. // 在作用域的结尾,资源会被回收
  360. // (即使有异常抛出,也一样会回收)
  361. }
  362. // 并行框架
  363. // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
  364. var websites = new string[] {
  365. "http://www.google.com", "http://www.reddit.com",
  366. "http://www.shaunmccarthy.com"
  367. };
  368. var responses = new Dictionary<string, string>();
  369. // 为每个请求新开一个线程
  370. // 在运行下一步前合并结果
  371. Parallel.ForEach(websites,
  372. new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
  373. website =>
  374. {
  375. // Do something that takes a long time on the file
  376. using (var r = WebRequest.Create(new Uri(website)).GetResponse())
  377. {
  378. responses[website] = r.ContentType;
  379. }
  380. });
  381. // 直到所有的请求完成后才会运行下面的代码
  382. foreach (var key in responses.Keys)
  383. Console.WriteLine("{0}:{1}", key, responses[key]);
  384. // 动态对象(配合其他语言使用很方便)
  385. dynamic student = new ExpandoObject();
  386. student.FirstName = "First Name"; // 不需要先定义类!
  387. // 你甚至可以添加方法(接受一个字符串,输出一个字符串)
  388. student.Introduce = new Func<string, string>(
  389. (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
  390. Console.WriteLine(student.Introduce("Beth"));
  391. // IQUERYABLE<T> - 几乎所有的集合都实现了它,
  392. // 带给你 Map / Filter / Reduce 风格的方法
  393. var bikes = new List<Bicycle>();
  394. bikes.Sort(); // Sorts the array
  395. bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // 根据车轮数排序
  396. var result = bikes
  397. .Where(b => b.Wheels > 3) // 筛选 - 可以连锁使用 (返回IQueryable)
  398. .Where(b => b.IsBroken && b.HasTassles)
  399. .Select(b => b.ToString()); // Map - 这里我们使用了select,所以结果是IQueryable<string>
  400. var sum = bikes.Sum(b => b.Wheels); // Reduce - 计算集合中的轮子总数
  401. // 创建一个包含基于自行车的一些参数生成的隐式对象的列表
  402. var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });
  403. // 很难演示,但是编译器在代码编译完成前就能推导出以上对象的类型
  404. foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
  405. Console.WriteLine(bikeSummary.Name);
  406. // ASPARALLEL
  407. // 邪恶的特性 —— 组合了linq和并行操作
  408. var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
  409. // 以上代码会并发地运行。会自动新开线程,分别计算结果。
  410. // 适用于多核、大数据量的场景。
  411. // LINQ - 将IQueryable<T>映射到存储,延缓执行
  412. // 例如 LinqToSql 映射数据库, LinqToXml 映射XML文档
  413. var db = new BikeRespository();
  414. // 执行被延迟了,这对于查询数据库来说很好
  415. var filter = db.Bikes.Where(b => b.HasTassles); // 不运行查询
  416. if (42 > 6) // 你可以不断地增加筛选,包括有条件的筛选,例如用于“高级搜索”功能
  417. filter = filter.Where(b => b.IsBroken); // 不运行查询
  418. var query = filter
  419. .OrderBy(b => b.Wheels)
  420. .ThenBy(b => b.Name)
  421. .Select(b => b.Name); // 仍然不运行查询
  422. // 现在运行查询,运行查询的时候会打开一个读取器,所以你迭代的是一个副本
  423. foreach (string bike in query)
  424. Console.WriteLine(result);
  425. }
  426. } // 结束LearnCSharp类
  427. // 你可以在同一个 .cs 文件中包含其他类
  428. public static class Extensions
  429. {
  430. // 扩展函数
  431. public static void Print(this object obj)
  432. {
  433. Console.WriteLine(obj.ToString());
  434. }
  435. }
  436. // 声明类的语法:
  437. // <public/private/protected/internal> class <类名>{
  438. // //数据字段, 构造器, 内部函数.
  439. / // 在Java中函数被称为方法。
  440. // }
  441. public class Bicycle
  442. {
  443. // 自行车的字段、变量
  444. public int Cadence // Public: 任何地方都可以访问
  445. {
  446. get // get - 定义获取属性的方法
  447. {
  448. return _cadence;
  449. }
  450. set // set - 定义设置属性的方法
  451. {
  452. _cadence = value; // value是被传递给setter的值
  453. }
  454. }
  455. private int _cadence;
  456. protected virtual int Gear // 类和子类可以访问
  457. {
  458. get; // 创建一个自动属性,无需成员字段
  459. set;
  460. }
  461. internal int Wheels // Internal:在同一程序集内可以访问
  462. {
  463. get;
  464. private set; // 可以给get/set方法添加修饰符
  465. }
  466. int _speed; // 默认为private: 只可以在这个类内访问,你也可以使用`private`关键词
  467. public string Name { get; set; }
  468. // enum类型包含一组常量
  469. // 它将名称映射到值(除非特别说明,是一个整型)
  470. // enmu元素的类型可以是byte、sbyte、short、ushort、int、uint、long、ulong。
  471. // enum不能包含相同的值。
  472. public enum BikeBrand
  473. {
  474. AIST,
  475. BMC,
  476. Electra = 42, //你可以显式地赋值
  477. Gitane // 43
  478. }
  479. // 我们在Bicycle类中定义的这个类型,所以它是一个内嵌类型。
  480. // 这个类以外的代码应当使用`Bicycle.Brand`来引用。
  481. public BikeBrand Brand; // 声明一个enum类型之后,我们可以声明这个类型的字段
  482. // 静态方法的类型为自身,不属于特定的对象。
  483. // 你无需引用对象就可以访问他们。
  484. // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated);
  485. static public int BicyclesCreated = 0;
  486. // 只读值在运行时确定
  487. // 它们只能在声明或构造器内被赋值
  488. readonly bool _hasCardsInSpokes = false; // read-only private
  489. // 构造器是创建类的一种方式
  490. // 下面是一个默认的构造器
  491. public Bicycle()
  492. {
  493. this.Gear = 1; // 你可以使用关键词this访问对象的成员
  494. Cadence = 50; // 不过你并不总是需要它
  495. _speed = 5;
  496. Name = "Bontrager";
  497. Brand = BikeBrand.AIST;
  498. BicyclesCreated++;
  499. }
  500. // 另一个构造器的例子(包含参数)
  501. public Bicycle(int startCadence, int startSpeed, int startGear,
  502. string name, bool hasCardsInSpokes, BikeBrand brand)
  503. : base() // 首先调用base
  504. {
  505. Gear = startGear;
  506. Cadence = startCadence;
  507. _speed = startSpeed;
  508. Name = name;
  509. _hasCardsInSpokes = hasCardsInSpokes;
  510. Brand = brand;
  511. }
  512. // 构造器可以连锁使用
  513. public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
  514. this(startCadence, startSpeed, 0, "big wheels", true, brand)
  515. {
  516. }
  517. // 函数语法
  518. // <public/private/protected> <返回值> <函数名称>(<参数>)
  519. // 类可以为字段实现 getters 和 setters 方法 for their fields
  520. // 或者可以实现属性(C#推荐使用这个)
  521. // 方法的参数可以有默认值
  522. // 在有默认值的情况下,调用方法的时候可以省略相应的参数
  523. public void SpeedUp(int increment = 1)
  524. {
  525. _speed += increment;
  526. }
  527. public void SlowDown(int decrement = 1)
  528. {
  529. _speed -= decrement;
  530. }
  531. // 属性可以访问和设置值
  532. // 当只需要访问数据的时候,考虑使用属性。
  533. // 属性可以定义get和set,或者是同时定义两者
  534. private bool _hasTassles; // private variable
  535. public bool HasTassles // public accessor
  536. {
  537. get { return _hasTassles; }
  538. set { _hasTassles = value; }
  539. }
  540. // 你可以在一行之内定义自动属性
  541. // 这个语法会自动创建后备字段
  542. // 你可以给getter或setter设置访问修饰符
  543. // 以便限制它们的访问
  544. public bool IsBroken { get; private set; }
  545. // 属性的实现可以是自动的
  546. public int FrameSize
  547. {
  548. get;
  549. // 你可以给get或set指定访问修饰符
  550. // 以下代码意味着只有Bicycle类可以调用Framesize的set
  551. private set;
  552. }
  553. //显示对象属性的方法
  554. public virtual string Info()
  555. {
  556. return "Gear: " + Gear +
  557. " Cadence: " + Cadence +
  558. " Speed: " + _speed +
  559. " Name: " + Name +
  560. " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") +
  561. "\n------------------------------\n"
  562. ;
  563. }
  564. // 方法可以是静态的。通常用于辅助方法。
  565. public static bool DidWeCreateEnoughBycles()
  566. {
  567. // 在静态方法中,你只能引用类的静态成员
  568. return BicyclesCreated > 9000;
  569. } // 如果你的类只需要静态成员,考虑将整个类作为静态类。
  570. } // Bicycle类结束
  571. // PennyFarthing是Bicycle的一个子类
  572. class PennyFarthing : Bicycle
  573. {
  574. // (Penny Farthings是一种前轮很大的自行车。没有齿轮。)
  575. // 调用父构造器
  576. public PennyFarthing(int startCadence, int startSpeed) :
  577. base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra)
  578. {
  579. }
  580. protected override int Gear
  581. {
  582. get
  583. {
  584. return 0;
  585. }
  586. set
  587. {
  588. throw new ArgumentException("你不可能在PennyFarthing上切换齿轮");
  589. }
  590. }
  591. public override string Info()
  592. {
  593. string result = "PennyFarthing bicycle ";
  594. result += base.ToString(); // 调用父方法
  595. return result;
  596. }
  597. }
  598. // 接口只包含成员的签名,而没有实现。
  599. interface IJumpable
  600. {
  601. void Jump(int meters); // 所有接口成员是隐式地公开的
  602. }
  603. interface IBreakable
  604. {
  605. bool Broken { get; } // 接口可以包含属性、方法和事件
  606. }
  607. // 类只能继承一个类,但是可以实现任意数量的接口
  608. {
  609. int damage = 0;
  610. public void Jump(int meters)
  611. {
  612. damage += meters;
  613. }
  614. public bool Broken
  615. {
  616. get
  617. {
  618. return damage > 100;
  619. }
  620. }
  621. }
  622. /// <summary>
  623. /// 连接数据库,一个 LinqToSql的示例。
  624. /// EntityFramework Code First 很棒 (类似 Ruby的 ActiveRecord, 不过是双向的)
  625. /// http://msdn.microsoft.com/en-us/data/jj193542.aspx
  626. /// </summary>
  627. public class BikeRespository : DbSet
  628. {
  629. public BikeRespository()
  630. : base()
  631. {
  632. }
  633. public DbSet<Bicycle> Bikes { get; set; }
  634. }
  635. } // 结束 Namespace

没有涉及到的主题

  • Flags
  • Attributes
  • 静态属性
  • Exceptions, Abstraction
  • ASP.NET (Web Forms/MVC/WebMatrix)
  • Winforms
  • Windows Presentation Foundation (WPF)

扩展阅读


还没有评论.