文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C# Foundation

C# Foundation

时间:2011-05-29  来源:ideasea

1. 数值类型 

整数字面量: 

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

实数字面量: 

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

数值字面量类型推定: 

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

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

数值字面量后缀: 

float f = 1.0F;
double d = 1D;
decimal d = 1.0M;
uint i = 1U;
ulong i = 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

字符串字面量: 

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

3. 布尔类型 

bool flag = true;

4. 数组 

默认元素初始化: 

//element of value type
public struct Point { public int X, Y; }
Point[] p
= new Point[1000];
int x = p[500].X; //0

//element of reference type
public 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}
};

5. 类 

public class Car
{
}

类成员: 

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

字段: 

class Car
{
private string name;
}

字段初始化语法: 

private int age = 10; //run before constructors

只读字段: 

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

常量: 

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

//local constant
static void Main()
{
const double twoPI = 2 * System.Math.PI;
}

实例构造函数: 

public class Car
{
public Car(){ }
}

构造函数重载: 

public class Person
{
public Person(string name)
{

}

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

}
}

静态构造函数: 

class Car
{
static Car() {}
}

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

属性: 

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; }
}

索引器: 

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

方法:

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 error

void Foo (ref int x); //OK so far
void Foo (out int x); //Compile-time error

void Goo (int[] x);
void Goo (params int[] x); //Compile-time error

可选参数: 

void Foo (int x = 23) {}

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

命名参数: 

void Foo (int x, int y) {}

Foo (x:
1, y:2);
Foo (
1, y:2);

Foo (x:
1, 2); //Compile-time error

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

操作符函数: 

//operator overloading
public static Complex operator+(Complex c1,Complex c2){...}

//implicit conversion overloading
public static implicit operator Complex(Int32 value{...}

//explicit conversion overloading
public static explicit operator Int32(Complex c){...}

终结器: 

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

编译为:

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

对象初始化器: 

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 };

分部类和方法: 

partial class PaymentForm //In auto-generated file
{
//...
partial void ValidatePayment (decimal amount);
}

partial class PaymentForm //In hand-authored file
{
//...
partial void ValidatePayment (decimal amount)
{
//...
}
}

继承: 

public class Asset
{
public string Name { get; set; }
//virtual method
public virtual decimal Liability { get { return 0; } }
}

public class Stock : Asset
{
public long SharesOwned { get; set; }
}

public class House : Asset
{
public decimal Mortgage { get; set; }
//override method
public override decimal Liability { get { return Mortgage; } }
}

构造函数和继承: 

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
}
}

6. 结构 

public struct Point
{
}

struct是值类型,不支持显示继承(隐式继承自System.ValueType)。

struct不能有终结器,虚成员。

struct不能显示的定义无参构造函数,隐式无参构造函数对所有字段执行bitwise-zeroing初始化。

struct的显示构造函数必须给所有字段显示赋值。

struct不能用字段初始化语法初始化字段。

装箱和拆箱: 

int x = 9;
object obj1 = x; //Box the int
int y = (int)obj1; //Unbox the int

object obj2 = 9; //9 is inferred to be of type int
long z = (long) obj2; //InvalidCastException

//Copying semantics
int i = 3;
object boxed = i;
i
= 5;
Console.WriteLine (boxed);
//3

7. 接口

public interface IRunnable
{
void Run();
}

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

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

扩展接口: 

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

显示接口实现: 

interface I1 { void Foo(); }
interface I2 { int Foo(); }

public class Widget : I1, I2
{
public void Foo ()
{
}

int I2.Foo()
{
}
}

8. 枚举

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

enum是值类型,隐式继承自System.Enum。

标志枚举: 

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

检测枚举有效性:

//Enum.IsDefined
public static bool IsDefined(Type enumType, Object value)

//custom method for flag enum
static bool IsFlagDefined (Enum e)
{
decimal d;
return !decimal.TryParse(e.ToString(), out d);
}

9. 泛型

泛型类型: 

public class Stack<T>
{
public void Push (T obj)
{
}

public T Pop()
{
}
}

Stack
<int> stack = new Stack<int>();

泛型方法: 

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

泛型约束: 

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

协变: 

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());

10. 委托 

delegate int Transformer (int x);

泛型委托: 

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 T16

delegate 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 object ObjectRetriever();

class Test
{
static void Main()
{
ObjectRetriever o
= new ObjectRetriever (RetriveString);
object result = o();
Console.WriteLine (result);
//hello
}

static string RetriveString() { return "hello"; }
}

逆变(参数): 

delegate void StringAction (string s);

class Test
{
static void Main()
{
StringAction sa
= new StringAction (ActOnObject);
sa (
"hello");
}

static void ActOnObject (object o)
{
Console.WriteLine (o);
//hello
}
}

泛型类型参数协变: 

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;

11. 事件

public event EventHandler<PriceChangedEventArgs> PriceChanged;

event提供了一个delegate的功能子集。

标准事件模式: 

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
+= stock_PriceChanged;

static void Stock_PriceChanged (object sender, PriceChangedEventArgs e)
{
}

事件访问器: 

private EventHandler _priceChanged; // Declare a private delegate

public event EventHandler PriceChanged
{
add { _priceChanged
+= value; }
remove { _priceChanged
-= value; }
}

12. Lambda表达式

//lambda expression
Func<int,int> sqr = x => x * x;

//lambda statement
Func<int,int> sqr = x => { return x * x; };

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

显示指定Lambda表达式参数类型:

Func<int,int> sqr = (int x) => x * x;

13. 枚举集合和迭代器 

枚举集合: 

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 iterating
foreach (char c in "beer")
{
//...
}

//low-level way of iterating
using (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>之一。


14. 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; //implicit
int y = (int)x; //explicit

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

装箱和拆箱Nullable值: 

当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 5
int? a = null, b = 1, c = 2;
Console.WriteLine (a
?? b ?? c); //1 (first non-null value)

15. 扩展方法

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"));

接口扩展方法: 

static void Main()
{
string[] strings = { "a", "b", null, "c"};
strings.StripNulls();
}

static IEnumerable<T> StripNulls<T> (this IEnumerable<T> seq)
{
foreach (T t in seq)
if (t != null)
yield return t;
}

16. 匿名类型 

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

17. 特性 

public sealed class ObsoleteAttribute : Attribute {...}

[ObsoleteAttribute]
public class Foo {...}

[Obsolete]
public class Foo {...}

命名和位置特性参数

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

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

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


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载