C# Foundation

依然范特西╮ 提交于 2020-01-03 23:21:25

一、值类型

1. 数值

整数字面量: 

int x = 100; //decimal notationlong y = 0x7F; //hexadecimal notation

实数字面量: 

double x = 1.5; //decimal notationdouble y = 1E06; //exponential notation

数值字面量类型推定:

如果数值字面量包含一个小数点或者包含指数部分(E),则为double类型。

否则,数值字面量是下面第一个能适配的类型:int, uint, long, ulong

数值字面量后缀: 

float f = 1.0F;double d = 1D;decimal m = 1.0M;uint u = 1U;ulong ul = 1UL;

特殊Float值:

float.NaN

float.PositiveInfinity

float.NegativeInfinity

-0.0F

特殊Double值:

double.NaN

double.PositiveInfinity

double.NegativeInfinity

-0.0


2. 字符

字符字面量:

char c = 'A';

字符转义序列:

\'      Single quote

\"      Double quote

\\      Backslash

\0      Null

\a      Alert

\b      Backspace

\f      Form feed

\n      New line

\r      Carriage return

\t      Horizontal tab

\v      Vertical tab

\uXXXX  Unicode character


3. 布尔值 

bool flag = true;

4. 枚举 

public enum BorderSide { Left, Right, Top, Bottom }

enum隐式继承自System.Enum。

标志枚举: 

[Flags]public enum BorderSides { Left=1, Right=2, Top=4, Bottom=8 }

检测枚举有效性: 

//Enum.IsDefinedpublic static bool IsDefined(Type enumType, Object value)//custom method for flag enumstatic bool IsFlagDefined (Enum e){  decimal d;  return !decimal.TryParse(e.ToString(), out d);}

5. 结构 

public struct Point{}

结构成员:

常量,构造器,字段,属性,索引器,方法,事件,操作符,内嵌类型。

struct不能显示定义无参实例构造器

struct隐式无参实例构造器对所有实例字段执行bitwise-zeroing初始化。

struct显示定义的实例构造器必须给所有实例字段显示赋值。

struct实例字段不支持字段初始化器。

struct不能定义终结器。

继承: 

public struct Point: IEquitable<Point>{}

struct隐式继承自System.ValueType。

struct能够实现接口。

struct不能被继承。

装箱和拆箱: 

int x = 9;object obj = x; //Box the intint y = (int)obj; //Unbox the int//exactly matching semanticsobject obj = 9; //9 is inferred to be of type intlong z = (long) obj; //InvalidCastException//copying semanticsint i = 3;object boxed = i;i = 5;Console.WriteLine (boxed); //3

分部结构: 

public partial struct PartiaStruct //In auto-generated file{  public void Method1(){ }}public partial struct PartialStruct //In hand-authored file{  public void Method2(){ }}

6. Nullable<T> 结构 

int? i = null;Console.WriteLine (i == null); //True

编译为: 

Nullable<int> i = new Nullable<int>();Console.WriteLine (! i.HasValue); //True

当HasValue返回false时,尝试查询Value将抛出InvalidOperationException。

当HasValue返回true时,GetValueOrDefault() 返回Value;否则返回new T()或指定的默认值。

隐式和显示Nullable转换: 

int? x = 5; //implicitint y = (int)x; //explicit

显示转换等价于直接调用Value属性。

装箱和拆箱Nullable值:

int? i = null;object o = i; //o is nulli = 5;o = i; //o refers to a boxed intint? a = (int?)o; //unbox into int?int b = (int)o; //unbox into int

当T?被装箱时,在堆上的装箱值包含T,而不是T?。

C#允许用as操作符拆箱Nullable类型。如果转换失败将返回null 

object o = "string";int? x = o as int?;Console.WriteLine (x.HasValue); //False

??操作符: 

int? x = null;int y = x ?? 5; //y is 5int? a = null, b = 1, c = 2;Console.WriteLine (a ?? b ?? c); //1 (first non-null value)

二、引用类型 

1. 字符串

字符串字面量: 

string s="Welcome";

逐字字符串字面量: 

string escaped = "<customer id=\"123\">\r\n</customer>";string verbatim = @"<customer id=""123""></customer>";//Assuming your IDE uses CR-LF line separators:Console.WriteLine(escaped==verbatim); //True

2.  

public class Car{}

类成员:

常量,字段,构造器,属性,索引器,方法,事件,操作符,内嵌类型,终结器。

抽象类: 

public abstract class AbstractClass{}

抽象类不能被直接实例化。

密封类: 

public sealed class SealedClass{}

密封类不能被继承。

静态类: 

public static class StaticClass{}

静态类隐式继承System.Object。

静态类不能被继承。

静态类不能被实例化。

静态类只能包含静态成员。

对象初始化器: 

public class Person{  public string Name{ get; set; }  public int Age{ get; set; }  public Person(){ }  public Person(string name){ }}Person p1 = new Person{ Name = "Jason", Age = 30 };Person p2 = new Person("Jason"){ Age = 30 };

继承: 

public class BaseClass{  //sealed method by default  public void Method1(){ }  //abstract method  public abstract void Method2();  //virtual method  public virtual void Method3(){ }}public class SubClass : BaseClass{  //override a abstract method  public override void Method2(){ }  //override and seal a virtual method  public override sealed Method3(){ }}

构造函数和继承: 

public class Baseclass{  public Baseclass () { }  public Baseclass (int x) { }}public class Subclass : Baseclass{  //implicit calling of the parameterless base class constructor  public Subclass (int x) : { }  public Subclass (int x, int y) : base (x) { }}

构造函数和字段初始化顺序: 

public class B{  int x = 0; //executes 3rd  public B (int x)  {    //executes 4th  }}public class S : B{  int x = 0; //executes 1st  public S (int x)    : base (x + 1) //executes 2nd  {    //executes 5th  }}

分部类: 

public partial class PartialClass //In auto-generated file{  public void Method1(){ }}public partial class PartialClass //In hand-authored file{  public void Method2(){ }}

3. 接口 

public interface IRunnable{  void Run();}internal class Car : IRunnable{  public void Run(){ }}

隐式接口实现成员默认为sealed。可标记为virtual。显示接口实现成员不能标记为virtual

接口成员:

属性,索引器,方法,事件。

接口成员总是隐式为abstract

接口成员总是隐式为public

扩展接口: 

public interface IUndoable { void Undo(); }public interface IRedoable : IUndoable { void Redo(); }

显示接口实现: 

public interface I1 { void Foo(); }public interface I2 { int Foo(); }public class Widget : I1, I2{  public void Foo () { }  int I2.Foo() { }}

分部接口: 

public partial interface PartialInterface //In auto-generated file{  void Method1();}public partial interface PartialInterface //In hand-authored file{  void Method2();}

4. 数组 

char[] vowels = {'a','e','i','o','u'};

数组隐式继承System.Array。

默认元素初始化: 

//element of value typepublic struct Point { public int X, Y; }Point[] p = new Point[1000];int x = p[500].X; //0//element of reference typepublic class Point { public int X, Y; }Point[] p = new Point[1000];int x = p[500].X; //Runtime error, NullReferenceException

数组初始化器: 

char[] vowels = {'a', 'e', 'i', 'o', 'u'};int[,] rectangularMatrix ={  {0, 1, 2},  {3, 4, 5},  {6, 7, 8}};int[][] jaggedMatrix ={  new int[] {0, 1, 2},  new int[] {3, 4, 5},  new int[] {6, 7, 8}};

或者 

var vowels = new char[]{'a', 'e', 'i', 'o', 'u'};var rectangularMatrix = new int[,]{  {0, 1, 2},  {3, 4, 5},  {6, 7, 8}};var jaggedMatrix = new int[][]{  new int[] {0, 1, 2},  new int[] {3, 4, 5},  new int[] {6, 7, 8}};

协变: 

Bear[] bears = new Bear[3];Animal[] animals = bears; // OKanimals[0] = new Camel(); // Runtime error

数组元素必须是引用类型。


5. 委托 

delegate int Transformer (int x);

协变(返回值): 

delegate object ObjectRetriever();static string RetriveString() { }ObjectRetriever o = RetriveString;

逆变(参数): 

delegate void StringAction (string s);static void ActOnObject (object o){ }StringAction sa = ActOnObject;

6. 异常 

public class CustomException: Exception{}

捕获异常: 

try{  //exception may get thrown within execution of this block}catch (ExceptionA ex){  //handle exception of type ExceptionA}catch (ExceptionB ex){  //handle exception of type ExceptionB}finally{  //cleanup code}

抛出异常:

//throw a new exceptionthrow new ArgumentNullException ("name");//rethrow same exceptionthrow;//rethrow a more specific exceptionthrow new XmlException ("Invalid DateTime", ex);

7. 特性

public sealed class ObsoleteAttribute : Attribute { }[ObsoleteAttribute]public class Foo { }[Obsolete]public class Foo { }

命名和位置特性参数:

[XmlElement ("Customer", Namespace="http://oreilly.com")]public class CustomerEntity{ }

定位参数对应于特性的构造函数参数。命名参数对应于特性的公共字段或属性。

参数类型只能是byte, sbyte, short, ushort, int, uint, long, ulong, float, double, bool, char, string, object, System.Type, enum类型, 以及这些类型的一维数组。


8. 匿名类型

var dude = new { Name = "Bob", Age = 1 };

匿名类型是不可变的。也就是说匿名类型的属性都是只读的。


9. 集合
集合初始化器: 

var list = new List<int> {1, 2, 3};var dictionary=new Dictionary<string, int>{  {“Jesse”, 1}, {“Joyce”, 2}}

枚举集合:

class Enumerator //Typically implements IEnumerator or IEnumerator<T>{  public IteratorVariableType Current { get { } }  public bool MoveNext() { }}class Enumerable //Typically implements IEnumerable or IEnumerable<T>{  public Enumerator GetEnumerator() { }}//high-level way of iteratingforeach (char c in "beer"){  //...}//low-level way of iteratingusing (var enumerator = "beer".GetEnumerator()){  while (enumerator.MoveNext())  {    var element = enumerator.Current;    //...  }}

迭代器:

static IEnumerable<string> Foo (bool breakEarly){  yield return "One";  yield return "Two";  if (breakEarly)    yield break;  yield return "Three";}

迭代器必须返回IEnumerable, IEnumerable<T>, IEnumerator, IEnumerator<T>之一。


三、类型成员 

1. 常量

public class Test{  private const double twoPI = 2 * System.Math.PI;}

常量在编译时求值。

常量总是隐式为static


2. 字段

class Car{  private string name;}

字段初始化器:

private int age = 10; //run before constructors

只读字段:

readonly字段只能在字段初始化语法和构造函数内赋值。


3. 实例构造函数

public class Car{  public Car(){ }}

构造函数重载:

public class Person{  public Person(string name){ }  //this(name) executes first  public Person(string name, int age) : this(name){ }}

4. 静态构造函数

class Car{  static Car(){ }}

静态构造函数总是隐式为private

运行时自动调用静态构造函数(在实例化类型或访问类型的静态成员之前)。


5. 属性

public class Car{  private string name;  //Property  public string Name  {    get{ return name; }    set{ name=value; }  }}

只读属性:

decimal price, amount;public decimal Worth{  get { return price * amount; }}

自动属性:

public class Car{  public string Name{ get; set; }}

可访问性:

public string Name{  get{ return name; }  protected set{ name=value; }}

6. 索引器

public class Sentence{  public string this[int index]  {    get { }    set { }  }}

索引器的默认名称是Item。可以通过IndexerNameAttribute定制索引器名称。


7. 方法

public class Car{  public void Run(){ }}

方法重载:

void Foo (int x);void Foo (double x);void Foo (int x, float y);void Foo (float x, int y);float Foo (int x); //Compile-time errorvoid Foo (ref int x); //OK so farvoid Foo (out int x); //Compile-time errorvoid Goo (int[] x);void Goo (params int[] x); //Compile-time error

可选参数:

void Foo (int x = 23) { }

可选参数必须在所有必填参数之前(params除外)。可选参数也不能标记为refout

命名参数:

void Foo (int x, int y) { }Foo (x:1, y:2);Foo (1, y:2);Foo (x:1, 2); //Compile-time error

定位参数必须在命名参数之前。

扩展方法:

public static class StringHelper{  public static bool IsCapitalized (this string s)  {    if (string.IsNullOrEmpty(s)) return false;    return char.IsUpper (s[0]);  }}Console.WriteLine ("Perth".IsCapitalized());Console.WriteLine (StringHelper.IsCapitalized ("Perth"));

也可以为一个接口,结构,枚举,委托定义扩展方法。

分部方法:

public partial class PartialClass //In auto-generated file{  partial void PartialMethod(decimal amount);}public partial class PartialClass //In hand-authored file{  partial void PartialMethod(decimal amount)  {    //...  }}

分部方法总是隐式为private

Lambda表达式:

//lambda expressionFunc<int,int> sqr = x => x * x;//lambda statementFunc<int,int> sqr = x => { return x * x; };//explicitly specifying lambda parameter typesFunc<int,int> sqr = (int x) => x * x;

Lambda 表达式能够表示一个委托实例或一个表达式树(Expression<TDelegate>)。

8. 事件

public event EventHandler<PriceChangedEventArgs> PriceChanged;

event只支持+=和-=操作。

event只能被它的包容类触发。

标准事件模式:

public class PriceChangedEventArgs : EventArgs{  public PriceChangedEventArgs (decimal lastPrice, decimal newPrice)  {  }}public class Stock{  public event EventHandler<PriceChangedEventArgs> PriceChanged;  protected virtual void OnPriceChanged (PriceChangedEventArgs e)  {    var temp = PriceChanged;    if (temp != null) temp (this, e);  }}stock.PriceChanged += StockPriceChanged;public void StockPriceChanged (object sender, PriceChangedEventArgs e){}

事件访问器:

private EventHandler priceChanged; // Declare a private delegatepublic event EventHandler PriceChanged{  add { priceChanged += value; }  remove { priceChanged -= value; }}

9. 操作符

//operator overloadingpublic static Complex operator+(Complex c1,Complex c2){ }//implicit conversion overloadingpublic static implicit operator Complex(int value){ }//explicit conversion overloadingpublic static explicit operator int(Complex c){ }

10. 终结器:

class Car{  ~Car()  {    //...  }}

编译为:

protected override void Finalize(){  //...  base.Finalize();}

四、泛型 

1. 泛型类型

public class Stack<T>{  public void Push (T obj){ }  public T Pop(){ }}Stack<int> stack = new Stack<int>();

2. 泛型结构

public struct KeyValuePair<TKey,TValue>{  public TKey Key { get; }  public TValue Value { get; }}

3. 泛型接口

public interface IEquatable<T>{  bool Equals(T other)}

协变:

class Animal {}class Bear : Animal {}class Camel : Animal {}public interface IPoppable<out T> { T Pop(); }public class Stack<T> : IPoppable<T>{}var bears = new Stack<Bear>();bears.Push (new Bear());IPoppable<Animal> animals = bears;Animal a = animals.Pop();

逆变:

public interface IPushable<in T> { void Push (T obj); }public class Stack<T> : IPushable<T>{}IPushable<Animal> animals = new Stack<Animal>();IPushable<Bear> bears = animals;bears.Push (new Bear());

4. 泛型委托

public delegate T Transformer<T> (T arg);

Func和Action委托:

delegate TResult Func <out TResult> ();delegate TResult Func <in T, out TResult> (T arg);delegate TResult Func <in T1, in T2, out TResult> (T1 arg1, T2 arg2);//... and so on, up to T16delegate void Action ();delegate void Action <in T> (T arg);delegate void Action <in T1, in T2> (T1 arg1, T2 arg2);//... and so on, up to T16

协变:

delegate TResult Func<out TResult>();Func<string> x = ...;Func<object> y = x;

逆变:

delegate void Action<in T> (T arg);Action<object> x = ...;Action<string> y = x;

5. 泛型方法

static void Swap<T> (ref T a, ref T b){}

6. 泛型约束

where T : base-class //Base class constraint

where T : interface //Interface constraint

where T : class //Reference-type constraint

where T : struct //Value-type constraint (excludes Nullable types)

where T : new() //Parameterless constructor constraint

where U : T //Naked type constraint


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!