重载构造函数:

  1. using System;
  2.  
  3. public class Wine
  4. {
  5. public decimal Price;
  6. public int Year;
  7. public Wine (decimal price) { Price = price; }
  8. public Wine (decimal price, int year) : this (price) { Year = year; }
  9. }

对象初始化:

  1. public class Bunny
  2. {
  3. public string Name;
  4. public bool LikesCarrots;
  5. public bool LikesHumans;
  6.  
  7. public Bunny () {}
  8. public Bunny (string n) { Name = n; }
  9. }
  1. Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false };
  2. Bunny b2 = new Bunny ("Bo") { LikesCarrots=true, LikesHumans=false };

this引用:

  1. public class Panda
  2. {
  3. public Panda Mate;
  4.  
  5. public void Marry (Panda partner)
  6. {
  7. Mate = partner;
  8. partner.Mate = this;
  9. }
  10. }
  1. public class Test
  2. {
  3. string name;
  4. public Test (string name) { this.name = name; }
  5. }

属性:

  1. public class Stock
  2. {
  3. decimal currentPrice; // The private "backing" field
  4.  
  5. public decimal CurrentPrice // The public property
  6. {
  7. get { return currentPrice; } set { currentPrice = value; }
  8. }
  9. }

只读和已计算属性:

  1. public class Stock
  2. {
  3. string symbol;
  4. decimal purchasePrice, currentPrice;
  5. long sharesOwned;
  6.  
  7. public Stock (string symbol, decimal purchasePrice, long sharesOwned)
  8. {
  9. this.symbol = symbol;
  10. this.purchasePrice = currentPrice = purchasePrice;
  11. this.sharesOwned = sharesOwned;
  12. }
  13.  
  14. public decimal CurrentPrice { get { return currentPrice; }
  15. set { currentPrice = value; } }
  16. public string Symbol { get { return symbol; } }
  17. public decimal PurchasePrice { get { return purchasePrice; } }
  18. public long SharesOwned { get { return sharesOwned; } }
  19. public decimal Worth { get { return CurrentPrice*SharesOwned; } }
  20. }
  21.  
  22. class Test
  23. {
  24. static void Main()
  25. {
  26. Stock msft = new Stock ("MSFT", 20, 1000);
  27. Console.WriteLine (msft.Worth); // 20000
  28. msft.CurrentPrice = 30;
  29. Console.WriteLine (msft.Worth); // 30000
  30. }
  31. }

自动属性:

  1. public class Stock
  2. {
  3. // ...
  4. public decimal CurrentPrice { get; set; }
  5. }

get 和 set 访问:

  1. public class Foo
  2. {
  3. private decimal x;
  4. public decimal X
  5. {
  6. get {return x;}
  7. internal set {x = value;}
  8. }
  9. }

实现索引:

  1. public class Portfolio
  2. {
  3. Stock[] stocks;
  4. public Portfolio (int numberOfStocks)
  5. {
  6. stocks = new Stock [numberOfStocks];
  7. }
  8.  
  9. public int NumberOfStocks { get { return stocks.Length; } }
  10.  
  11. public Stock this [int index] // indexer
  12. {
  13. get { return stocks [index]; }
  14. set { stocks [index] = value; }
  15. }
  16. }
  17.  
  18. class Test
  19. {
  20. static void Main()
  21. {
  22. Portfolio portfolio = new Portfolio(3);
  23. portfolio [0] = new Stock ("MSFT", 20, 1000);
  24. portfolio [1] = new Stock ("GOOG", 300, 100);
  25. portfolio [2] = new Stock ("EBAY", 33, 77);
  26.  
  27. for (int i = 0; i < portfolio.NumberOfStocks; i++)
  28. Console.WriteLine (portfolio[i].Symbol);
  29. }
  30. }

多索引:

  1. public class Portfolio
  2. {
  3. ...
  4. public Stock this[string symbol]
  5. {
  6. get
  7. {
  8. foreach (Stock s in stocks)
  9. if (s.Symbol == symbol)
  10. return s;
  11. return null;
  12. }
  13. }
  14. }

静态构造函数:

  1. class Test
  2. {
  3. static Test()
  4. {
  5. Console.WriteLine ("Type Initialized");
  6. }
  7. }

Partial方法:

  1. // PaymentFormGen.cs — auto-generated
  2. partial class PaymentForm
  3. {
  4. // ...
  5. partial void ValidatePayment(decimal amount);
  6. }
  1. // PaymentForm.cs — hand-authored
  2. partial class PaymentForm
  3. {
  4. // ...
  5. // partial void ValidatePayment(decimal amount)
  6. {
  7. if (amount > 100)
  8. {
  9. // ...
  10. }
  11. }
  12. }

继承:

  1. public class Asset
  2. {
  3. public string Name;
  4. public decimal PurchasePrice, CurrentPrice;
  5. }
  1. public class Stock : Asset // inherits from Asset
  2. {
  3. public long SharesOwned;
  4. }
  5.  
  6. public class House : Asset // inherits from Asset
  7. {
  8. public decimal Mortgage;
  9. }
  10.  
  11. class Test
  12. {
  13. static void Main()
  14. {
  15. Stock msft = new Stock()
  16. { Name="MSFT", PurchasePrice=20, CurrentPrice=30, SharesOwned=1000 };
  17.  
  18. House mansion = new House
  19. { Name="McMansion", PurchasePrice=300000, CurrentPrice=200000,
  20. Mortgage=250000 };
  21.  
  22. Console.WriteLine (msft.Name); // MSFT
  23. Console.WriteLine (mansion.Name); // McMansion
  24.  
  25. Console.WriteLine (msft.SharesOwned); // 1000
  26. Console.WriteLine (mansion.Mortgage); // 250000
  27. }
  28. }

多态:

  1. class Test
  2. {
  3. static void Main()
  4. {
  5. Stock msft = new Stock ... ;
  6. House mansion = new House ... ;
  7. Display (msft);
  8. Display (mansion);
  9. }
  10.  
  11. public static void Display (Asset asset)
  12. {
  13. System.Console.WriteLine (asset.Name);
  14. }
  15. }
  1. static void Main() { Display (new Asset()); } // Compile-time error
  2.  
  3. public static void Display (House house) // Will not accept Asset
  4. {
  5. System.Console.WriteLine (house.Mortgage);
  6. }

向下转换:

  1. Stock msft = new Stock();
  2. Asset a = msft; // upcast
  3. Stock s = (Stock)a; // downcast
  4. Console.WriteLine (s.SharesOwned); // <No error>
  5. Console.WriteLine (s == a); // true
  6. Console.WriteLine (s == msft); // true

虚拟函数成员:

  1. public class Asset
  2. {
  3. ...
  4. public virtual decimal Liability { get { return 0; } }
  5. }
  1. public class Stock : Asset { ... }
  2.  
  3. public class House : Asset
  4. {
  5. ...
  6. public override decimal Liability { get { return Mortgage; } }
  7. }
  1. House mansion = new House
  2. { Name="McMansion", PurchasePrice=300000, CurrentPrice=200000,
  3. Mortgage=250000 };
  4.  
  5. Asset a = mansion;
  6. decimal d2 = mansion.Liability; // 250000

抽象类和抽象成员:

  1. public abstract class Asset
  2. {
  3. ...
  4. public abstract decimal NetValue { get; } // Note empty implementation
  5. }
  6.  
  7. public class Stock : Asset
  8. {
  9. ... // Override an abstract method
  10. public override decimal NetValue // just like a virtual method.
  11. {
  12. get { return CurrentPrice * SharesOwned; }
  13. }
  14. }
  15.  
  16. public class House : Asset // Every non abstract subtype must
  17. { // define NetValue.
  18. ...
  19. public override decimal NetValue
  20. {
  21. get { return CurrentPrice - Mortgage; }
  22. }
  23. }

new 和 virtual

  1. public class BaseClass
  2. {
  3. public virtual void Foo() { Console.WriteLine ("BaseClass.Foo"); }
  4. }
  5.  
  6. public class Overrider : BaseClass
  7. {
  8. public override void Foo() { Console.WriteLine ("Overrider.Foo"); }
  9. }
  10.  
  11. public class Hider : BaseClass
  12. {
  13. public new void Foo() { Console.WriteLine ("Hider.Foo"); }
  14. }
  1. Overrider o = new Overrider();
  2. BaseClass b1 = o;
  3. o.Foo(); // Overrider.Foo
  4. b1.Foo(); // Overrider.Foo
  5.  
  6. Hider h = new Hider();
  7. BaseClass b2 = h;
  8. h.Foo(); // Hider.Foo
  9. b2.Foo(); // BaseClass.Foo

GetType() 和 typeof

  1. using System;
  2.  
  3. public class Point {public int X, Y;}
  4.  
  5. class Test
  6. {
  7. static void Main()
  8. {
  9. Point p = new Point();
  10. Console.WriteLine (p.GetType().Name); // Point
  11. Console.WriteLine (typeof (Point).Name); // Point
  12. Console.WriteLine (p.GetType() == typeof(Point)); // True
  13. Console.WriteLine (p.X.GetType().Name); // Int32
  14. Console.WriteLine (p.Y.GetType().FullName); // System.Int32
  15. }
  16. }

显式接口实现:

  1. interface I1 { void Foo(); }
  2. interface I2 { int Foo(); }
  3.  
  4. public class Widget : I1, I2
  5. {
  6. public void Foo ()
  7. {
  8. Console.WriteLine ("Widget's implementation of I1.Foo");
  9. }
  10.  
  11. int I2.Foo ()
  12. {
  13. Console.WriteLine ("Widget's implementation of I2.Foo");
  14. return 42;
  15. }
  16. }
  1. Widget w = new Widget();
  2. w.Foo(); // Widget's implementation of I1.Foo
  3. ((I1)w).Foo(); // Widget's implementation of I1.Foo
  4. ((I2)w).Foo(); // Widget's implementation of I2.Foo

虚拟地实现接口成员:

  1. public interface IUndoable { void Undo(); }
  2.  
  3. public class TextBox : IUndoable
  4. {
  5. public virtual void Undo()
  6. {
  7. Console.WriteLine ("TextBox.Undo");
  8. }
  9. }
  10.  
  11. public class RichTextBox : TextBox
  12. {
  13. public override void Undo()
  14. {
  15. Console.WriteLine ("RichTextBox.Undo");
  16. }
  17. }
  1. RichTextBox r = new RichTextBox();
  2. r.Undo(); // RichTextBox.Undo
  3. ((IUndoable)r).Undo(); // RichTextBox.Undo
  4. ((TextBox)r).Undo(); // RichTextBox.Undo

在子类中重新实现一个接口:

  1. public interface IUndoable { void Undo(); }
  2.  
  3. public class TextBox : IUndoable
  4. {
  5. void IUndoable.Undo() { Console.WriteLine ("TextBox.Undo"); }
  6. }
  7.  
  8. public class RichTextBox : TextBox, IUndoable
  9. {
  10. public new void Undo() { Console.WriteLine ("RichTextBox.Undo"); }
  11. }
  1. RichTextBox r = new RichTextBox();
  2. r.Undo(); // RichTextBox.Undo Case 1
  3. ((IUndoable)r).Undo(); // RichTextBox.Undo Case 2
  1. public class TextBox : IUndoable
  2. {
  3. public void Undo() { Console.WriteLine ("TextBox.Undo"); }
  4. }
  1. RichTextBox r = new RichTextBox();
  2. r.Undo(); // RichTextBox.Undo Case 1
  3. ((IUndoable)r).Undo(); // RichTextBox.Undo Case 2
  4. ((TextBox)r).Undo(); // TextBox.Undo Case 3

替代接口重新实现:

  1. public class TextBox : IUndoable
  2. {
  3. void IUndoable.Undo() { Undo(); } // Calls method below
  4. protected virtual void Undo() { Console.WriteLine ("TextBox.Undo"); }
  5. }
  6.  
  7. public class RichTextBox : TextBox
  8. {
  9. protected override void Undo() { Console.WriteLine ("RichTextBox.Undo"); }
  10. }

Flags enums枚举:

  1. [Flags]
  2. public enum BorderSides { Left=1, Right=2, Top=4, Bottom=8 }
  1. BorderSides leftRight = BorderSides.Left | BorderSides.Right;
  2.  
  3. if ((leftRight & BorderSides.Left) != 0)
  4. System.Console.WriteLine ("Includes Left"); // Includes Left
  5.  
  6. string formatted = leftRight.ToString(); // "Left, Right"
  7.  
  8. BorderSides s = BorderSides.Left;
  9. s |= BorderSides.Right;
  10. Console.WriteLine (s == leftRight); // True
  11.  
  12. s ^= BorderSides.Right; // Toggles BorderSides.Right
  13. Console.WriteLine (s); // Left

Enum枚举类型安全问题:

  1. static bool IsFlagDefined (Enum e)
  2. {
  3. decimal d;
  4. return ! decimal.TryParse(e.ToString(), out d);
  5. }
  6.  
  7. [Flags]
  8. public enum BorderSides { Left=1, Right=2, Top=4, Bottom=8 }
  9.  
  10. static void Main()
  11. {
  12. for (int i = 0; i <= 16; i++)
  13. {
  14. BorderSides side = (BorderSides)i;
  15. Console.WriteLine (IsFlagDefined (side) + " " + side);
  16. }
  17. }

泛型:

  1. public class Stack<T>
  2. {
  3. int position;
  4. T[] data = new T[100];
  5. public void Push (T obj) { data[position++] = obj; }
  6. public T Pop () { return data[--position]; }
  7. }
  1. Stack<int> stack = new Stack<int>();
  2. stack.Push(5);
  3. stack.Push(10);
  4. int x = stack.Pop();

泛方法:

  1. static void Swap<T> (ref T a, ref T b)
  2. {
  3. T temp = b;
  4. a = b;
  5. b = temp;
  6. }

默认泛值:

  1. static void Zap<T> (T[] array)
  2. {
  3. for (int i = 0; i < array.Length; i++)
  4. array[i] = default(T);
  5. }

约束:

  1. static T Max <T> (T a, T b) where T : IComparable<T>
  2. {
  3. return a.CompareTo (b) > 0 ? a : b;
  4. }
  1. static void Initialize<T> (T[] array) where T : new()
  2. {
  3. for (int i = 0; i < array.Length; i++)
  4. array[i] = new T();
  5. }
  1. class Stack<T>
  2. {
  3. Stack<U> FilteredStack<U>() where U : T {...}
  4. }

泛型和协方差:

  1. class Animal {}
  2. class Bear : Animal {}
  1. public class ZooCleaner
  2. {
  3. public static void Wash<T> (Stack<T> animals) where T : Animal {}
  4. }
  1. Stack<Bear> bears = new Stack<Bear>();
  2. ZooCleaner.Wash (bears);

自引用泛型声明:

  1. interface IEquatable<T> { bool Equals (T obj); }
  2.  
  3. public class Balloon : IEquatable<Balloon>
  4. {
  5. string color;
  6. int cc;
  7.  
  8. public bool Equals (Balloon b)
  9. {
  10. if (b == null) return false;
  11. return b.color == color && b.cc == cc;
  12. }
  13. }

泛型类型中的静态数据的唯一性:

  1. public class Bob<T> { public static int Count; }
  2.  
  3. class Test
  4. {
  5. static void Main()
  6. {
  7. Console.WriteLine (++Bob<int>.Count); // 1
  8. Console.WriteLine (++Bob<int>.Count); // 2
  9. Console.WriteLine (++Bob<string>.Count); // 1
  10. Console.WriteLine (++Bob<object>.Count); // 1
  11. }
  12. }

对象初始化:

  1. List<int> list = new List<int> {1, 2, 3};

在C#中创建类型的更多相关文章

  1. C++中结构体与类的区别(结构不能被继承,默认是public,在堆栈中创建,是值类型,而类是引用类型)good

    结构是一种用关键字struct声明的自定义数据类型.与类相似,也可以包含构造函数,常数,字段,方法,属性,索引器,运算符和嵌套类型等,不过,结构是值类型. 1.结构的构造函数和类的构造函数不同. a. ...

  2. 关于Emit中动态类型TypeBuilder创建类标记的一点思考

      利用TypeBuilder是可以动态创建一个类型,现在有个需求,动态生成一个dll,创建类型EmployeeEx,需要继承原dll里面的Employee类,并包含Employee类上的所有类标记. ...

  3. 【转载】 Java中String类型的两种创建方式

    本文转载自 https://www.cnblogs.com/fguozhu/articles/2661055.html Java中String是一个特殊的包装类数据有两种创建形式: String s ...

  4. Java归去来第4集:java实战之Eclipse中创建Maven类型的SSM项目

    一.前言 如果还不了解剧情,请返回第3集的剧情          Java归去来第3集:Eclipse中给动态模块升级 二.在Eclipse中创建Maven类型的SSM项目 2.1:SSM简介 SSM ...

  5. 在 QML 中创建 C++ 导入类型的实例

    在 QML 中创建 C++ 导入类型的实例 文件列表: Project1.pro QT += quick CONFIG += c++ CONFIG += declarative_debug CONFI ...

  6. 受检查异常要求try catch,new对象时,就会在堆中创建内存空间,创建的空间包括各个成员变量类型所占用的内存空间

    ,new对象时,就会在堆中创建内存空间,创建的空间包括各个成员变量类型所占用的内存空间

  7. 图像处理中创建CDib类时无法选择基类类型时怎么办

    图像处理中创建CDib类时无法选择基类类型时怎么办? 类的类型选择Generic Class 在下面的篮筐里输入CObject就行了

  8. In-Memory:在内存中创建临时表和表变量

    在Disk-Base数据库中,由于临时表和表变量的数据存储在tempdb中,如果系统频繁地创建和更新临时表和表变量,大量的IO操作集中在tempdb中,tempdb很可能成为系统性能的瓶颈.在SQL ...

  9. 详解Linux交互式shell脚本中创建对话框实例教程_linux服务器

    本教程我们通过实现来讲讲Linux交互式shell脚本中创建各种各样对话框,对话框在Linux中可以友好的提示操作者,感兴趣的朋友可以参考学习一下. 当你在终端环境下安装新的软件时,你可以经常看到信息 ...

随机推荐

  1. 【恒天云】OpenStack和CloudStack对比研究报告

    摘自恒天云:http://www.hengtianyun.com/download-show-id-8.html 1. 概述 常见的IaaS开源平台有OpenStack.CloudStack.Euca ...

  2. Django中的Model(字段)

    Model Django中的model是用来操作数据库的,Model是一个ORM框架,我们只需要关心model的操作,而不需要关心到底是哪一种数据库. 一.基本知识: 数据库引擎: Django中自带 ...

  3. 自定义实现MPVolumeView音量控件

    http://blog.csdn.net/theonezh/article/details/8158420 http://www.cnblogs.com/cate/ios/ http://www.cn ...

  4. Stage3D学习笔记(四):正交矩阵

    我们上一章节显示图片的时候,会发现我们制定的顶点在Stage3D中其实是存在一个区间的: x轴(从左到右):[-1.0-1.0] y轴(从下到上):[-1.0-1.0] z轴(从近到远):[0-1.0 ...

  5. sudo: /etc/sudoers is mode 0640, should be 0440解决办法

    ubuntu或者CentOS中,/etc/sudoer 的权限为 0440时才能正常使用,否则sudo命令就不能正常使用.出现类似:sudo: /etc/sudoers is mode 0640, s ...

  6. hdu 5443 The Water Problem 线段树

    The Water Problem Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php? ...

  7. ios开发——实战OC篇&SQLite3的实际应用

    SQLite3的实际应用 前面的文章中介绍了SQlite,并且介绍了他的各种语法及使用方法. 但是没有正在项目中使用特,今天就开始做一个小小的实例,就是使用SQLite3来实现数据库的相应操作并且把他 ...

  8. iOS开发——UI篇OC篇&UITableView多项选择

    UITableView多项选择 自定义cell和取到相应的cell就行了 TableViewCell.h #import <UIKit/UIKit.h> @interface TableV ...

  9. BAPI_ACC_DOCUMENT_POST Enter rate / GBP rate type M for Error SG105

    Folks, I was wondering if I could get a bit of help here as I've been racking my brains on it for ag ...

  10. 进程关系之tcgetpgrp、tcsetpgrp和tcgetsid函数

    需要有一种方法来通知内核哪一个进程组是前台进程组,这样,终端设备驱动程序就能了解将终端输入和终端产生的信号送到何处. #include <unistd.h> pid_t tcgetpgrp ...