标签:参考 time express describes san dll 通过 ultimate contain
from: ms-docs
关于C#编译器的安装和使用,请参考另一篇博客:《C#环境搭建,以及C#编译器的使用》
sbyte
, short
, int
, long
byte
, ushort
, uint
, ulong
char
float
, double
decimal
bool
enum E {...}
struct S {...}
null
valueobject
string
class C {...}
interface I {...}
int[]
and int[,]
delegate int D(...)
x.m
: Member accessx(...)
: Method and delegate invocationx[...]
: Array and indexer accessx++
: Post-incrementx--
: Post-decrementnew T(...)
: Object and delegate creationnew T(...){...}
: Object creation with initializernew {...}
: Anonymous object initializernew T[...]
: Array creationtypeof(T)
: Obtain Type object for T
checked(x)
: Evaluate expression in checked contextunchecked(x)
: Evaluate expression in unchecked contextdefault(T)
: Obtain default value of type T
delegate {...}
: Anonymous function (anonymous method)+x
: Identity-x
: Negation!x
: Logical negation~x
: Bitwise negation++x
: Pre-increment--x
: Pre-decrement(T)x
: Explicitly convert x
to type T
await x
: Asynchronously wait for x
to completex * y
: Multiplicationx / y
: Divisionx % y
: Remainderx + y
: Addition, string concatenation, delegate combinationx - y
: Subtraction, delegate removalx << y
: Shift leftx >> y
: Shift rightx < y
: Less thanx > y
: Greater thanx <= y
: Less than or equalx >= y
: Greater than or equal x is T
: Return true
if x
is a T
, false
otherwise x as T
: Return x
typed as T
, or null
if x
is not a T
x == y
: Equalx != y
: Not equalx & y
: Integer bitwise AND, boolean logical ANDx ^ y
: Integer bitwise XOR, boolean logical XORx | y
: Integer bitwise OR, boolean logical ORx && y
: Evaluates y
only if x
is not false
x || y
: Evaluates y
only if x
is not true
x ?? y
: Evaluates to y
if x
is null, to x
otherwisex ? y : z
: Evaluates y
if x
is true
, z
if x
is false
x = y
: Assignmentx op= y
: Compound assignment; supported operators are
*=
/=
%=
+=
-=
<<=
>>=
&=
^=
|=
(T x) => y
: Anonymous function (lambda expression)Selection statements are used to select one of a number of possible statements for execution based on the value of some expression. In this group are the if
and switch
statements.
{ int n = args.Length; switch (n) { case 0: Console.WriteLine("No arguments"); break; case 1: Console.WriteLine("One argument"); break; default: Console.WriteLine($"{n} arguments"); break; } }
Iteration statements are used to execute repeatedly an embedded statement. In this group are the while
, do
, for
, and foreach
statements.
{ foreach (string s in args) { Console.WriteLine(s); } }
Jump statements are used to transfer control. In this group are the break
, continue
, goto
, throw
, return
, and yield
statements.
{ int i = 0; goto check; loop: Console.WriteLine(args[i++]); check: if (i < args.Length) goto loop; }
{ for (int i = from; i < to; i++) { yield return i; } yield break; } static void YieldStatement(string[] args) { foreach (int i in Range(-10,10)) { Console.WriteLine(i); } }
The try
...catch
statement is used to catch exceptions that occur during execution of a block, and the try
...finally
statement is used to specify finalization code that is always executed, whether an exception occurred or not.
{ if (y == 0) throw new DivideByZeroException(); return x / y; } static void TryCatch(string[] args) { try { if (args.Length != 2) { throw new InvalidOperationException("Two numbers required"); } double x = double.Parse(args[0]); double y = double.Parse(args[1]); Console.WriteLine(Divide(x, y)); } catch (InvalidOperationException e) { Console.WriteLine(e.Message); } finally { Console.WriteLine("Good bye!"); } }
The checked
and unchecked
statements are used to control the overflow-checking context for integral-type arithmetic operations and conversions.
{ int x = int.MaxValue; unchecked { Console.WriteLine(x + 1); // Overflow } checked { Console.WriteLine(x + 1); // Exception } }
The lock
statement is used to obtain the mutual-exclusion lock for a given object, execute a statement, and then release the lock.
{ decimal balance; private readonly object sync = new object(); public void Withdraw(decimal amount) { lock (sync) { if (amount > balance) { throw new Exception( "Insufficient funds"); } balance -= amount; } } }
The using
statement is used to obtain a resource, execute a statement, and then dispose of that resource.
{ using (TextWriter w = File.CreateText("test.txt")) { w.WriteLine("Line one"); w.WriteLine("Line two"); w.WriteLine("Line three"); } }
The members of a class are either static members or instance members. Static members belong to classes, and instance members belong to objects (instances of classes).
The following provides an overview of the kinds of members a class can contain.
Each member of a class has an associated accessibility, which controls the regions of program text that are able to access the member. There are six possible forms of accessibility. These are summarized below.
public class Pair<TFirst,TSecond> { public TFirst First; public TSecond Second; } // try to use it Pair<int,string> pair = new Pair<int,string> { First = 1, Second = "two" }; int i = pair.First; // TFirst is int string s = pair.Second; // TSecond is string
A method is a member that implements a computation or action that can be performed by an object or class. Static methods are accessed through the class. Instance methods are accessed through instances of the class.
Method Parameters are used to pass values or variable references to methods. The parameters of a method get their actual values from the arguments that are specified when the method is invoked. There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.
static void Swap(ref int x, ref int y) { int temp = x; x = y; y = temp; } public static void SwapExample() { int i = 1, j = 2; Swap(ref i, ref j); Console.WriteLine($"{i} {j}"); // Outputs "2 1" } ------------------------------------------------------------------------------- static void Divide(int x, int y, out int result, out int remainder) { result = x / y; remainder = x % y; } public static void OutUsage() { Divide(10, 3, out int res, out int rem); Console.WriteLine("{0} {1}", res, rem); // Outputs "3 1" }
-------------------------------------------------------------------------------
public class Console{ public static void Write(string fmt, params object[] args) { } public static void WriteLine(string fmt, params object[] args) { } // ... }
When an instance method declaration includes a virtual modifier, the method is said to be a virtual method. When no virtual modifier is present, the method is said to be a nonvirtual method.
When a virtual method is invoked, the run-time type of the instance for which that invocation takes place determines the actual method implementation to invoke. In a nonvirtual method invocation, the compile-time type of the instance is the determining factor.
public abstract class Expression { public abstract double Evaluate(Dictionary<string,object> vars); } public class Constant: Expression { double value; public Constant(double value) { this.value = value; } public override double Evaluate(Dictionary<string,object> vars) { return value; } }
Method overloading permits multiple methods in the same class to have the same name as long as they have unique signatures. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.
This section describes the other kinds of function members supported by C#: constructors, properties, indexers, events, operators, and finalizers.
1 public class List<T> 2 { 3 // Constant 4 const int defaultCapacity = 4; 5 6 // Fields 7 T[] items; 8 int count; 9 10 // Constructor 11 public List(int capacity = defaultCapacity) { 12 items = new T[capacity]; 13 } 14 15 // Properties 16 public int Count => count; 17 18 public int Capacity { 19 get { return items.Length; } 20 set { 21 if (value < count) value = count; 22 if (value != items.Length) { 23 T[] newItems = new T[value]; 24 Array.Copy(items, 0, newItems, 0, count); 25 items = newItems; 26 } 27 } 28 } 29 30 // Indexer 31 public T this[int index] { 32 get { 33 return items[index]; 34 } 35 set { 36 items[index] = value; 37 OnChanged(); 38 } 39 } 40 41 // Methods 42 public void Add(T item) { 43 if (count == Capacity) Capacity = count * 2; 44 items[count] = item; 45 count++; 46 OnChanged(); 47 } 48 49 protected virtual void OnChanged() => 50 Changed?.Invoke(this, EventArgs.Empty); 51 52 public override bool Equals(object other) => 53 Equals(this, other as List<T>); 54 55 static bool Equals(List<T> a, List<T> b) { 56 if (Object.ReferenceEquals(a, null)) return Object.ReferenceEquals(b, null); 57 if (Object.ReferenceEquals(b, null) || a.count != b.count) 58 return false; 59 for (int i = 0; i < a.count; i++) { 60 if (!object.Equals(a.items[i], b.items[i])) { 61 return false; 62 } 63 } 64 return true; 65 } 66 67 // Event 68 public event EventHandler Changed; 69 70 // Operators 71 public static bool operator ==(List<T> a, List<T> b) => 72 Equals(a, b); 73 74 public static bool operator !=(List<T> a, List<T> b) => 75 !Equals(a, b); 76 }
C# 支持实例和静态构造函数。 实例构造函数是实现初始化类实例所需执行的操作的成员。 静态构造函数是实现在首次加载类时初始化类本身所需执行的操作的成员。
与其他成员不同,实例构造函数不能被继承,且类中只能包含实际已声明的实例构造函数。 如果没有为类提供实例构造函数,则会自动提供不含参数的空实例构造函数。
属性是字段的自然扩展。 与字段不同的是,属性不指明存储位置。 相反,属性包含访问器,用于指定在读取或写入属性值时要执行的语句。
List<string> names = new List<string>(); names.Capacity = 100; // Invokes set accessor int i = names.Count; // Invokes get accessor int j = names.Capacity; // Invokes get accessor
Similar to fields and methods, C# supports both instance properties and static properties. Static properties are declared with the static modifier, and instance properties are declared without it.
The accessor(s) of a property can be virtual. When a property declaration includes a virtual
, abstract
, or override
modifier, it applies to the accessor(s) of the property.
借助索引器成员,可以将对象编入索引(像处理数组一样)。 索引器的声明方式与属性类似,不同之处在于,索引器成员名称格式为后跟分隔符 [ 和 ],其中写入参数列表。 这些参数在索引器的访问器中可用。 类似于属性,索引器分为读写、只读和只写索引器,且索引器的访问器可以是的 virtual 修饰 。
List<string> names = new List<string>(); names.Add("Liz"); names.Add("Martha"); names.Add("Beth"); for (int i = 0; i < names.Count; i++) { string s = names[i]; names[i] = s.ToUpper(); }
索引器可以进行重载。也就是说,类可以声明多个索引器,只要其参数的数量或类型不同即可。
借助事件成员,类或对象可以提供通知。 事件的声明方式与字段类似,不同之处在于,事件声明包括事件关键字,且类型必须是委托类型。
在声明事件成员的类中,事件的行为与委托类型的字段完全相同(前提是事件不是抽象的,且不声明访问器)。 字段存储对委托的引用,委托表示已添加到事件的事件处理程序。 如果没有任何事件处理程序,则字段为 null。
List<T> 类声明一个 Changed 事件成员,指明已向列表添加了新项。 Changed 事件由 OnChanged 虚方法引发,此方法会先检查事件是否是 null(即不含任何处理程序)。 引发事件的概念恰恰等同于调用由事件表示的委托,因此,没有用于引发事件的特殊语言构造。
客户端通过事件处理程序响应事件。 使用 += 和 -= 运算符分别可以附加和删除事件处理程序。
class EventExample { static int changeCount; static void ListChanged(object sender, EventArgs e) { changeCount++; } public static void Usage() { List<string> names = new List<string>(); names.Changed += new EventHandler(ListChanged); names.Add("Liz"); names.Add("Martha"); names.Add("Beth"); Console.WriteLine(changeCount); // Outputs "3" } }
对于需要控制事件的基础存储的高级方案,事件声明可以显式提供 add 和 remove 访问器,这在某种程度上与属性的 set 访问器类似。
运算符是定义向类实例应用特定表达式运算符的含义的成员。 可以定义三种类型的运算符:一元运算符、二元运算符和转换运算符。 所有运算符都必须声明为 public
和 static
。
终结器既不能包含参数和可访问性修饰符,也不能进行显式调用。 实例的终结器在垃圾回收期间自动调用。
垃圾回收器在决定何时收集对象和运行终结器时有很大自由度。 具体来说,终结器的调用时间具有不确定性,可以在任意线程上执行终结器。For these and other reasons, classes should implement finalizers only when no other solutions are feasible.
处理对象析构的更好方法是使用 using 语句。
标签:参考 time express describes san dll 通过 ultimate contain
原文地址:https://www.cnblogs.com/brt3/p/9734503.html