C#的编码规范中文版

本文详细介绍了C#编程的命名规范,包括类、方法、变量的命名规则,以及代码组织、注释、异常处理、类型使用、文件命名、接口实现等方面的最佳实践。强调了使用有意义的命名、避免硬编码、使用接口、避免显式类型转换等原则,旨在提高代码的可读性和维护性。
部署运行你感兴趣的模型镜像
1.命名规范
1. 使用 Pascal casing 定义类型和方法名
public class SomeClass
{
   public SomeMethod(){}
}
2. 使用 camel casing 定义局部变量名和方法参数
int number;
void MyMethod(int someNumber)
{}
3. 使用“I”前缀定义接口名
interface IMyInterface
{..}
4. 使用“m_”前缀定义私有成员变量
public class SomeClass
{
   private int m_Number;
}
5. 属性类使用“Attribute”为后缀
6. 异常类使用“ Exception.”为后缀
7. 方法命名采用动词短语,例如ShowDialog()
8. 带返回值的方法应该在名字中描述返回值,例如 GetObjectState()
9. 一般地,命名参数的时候加上TYPE. 这将增加代码的易读性
//正确:
public class LinkedList<KeyType,DataType>
{…}
//避免:
public class LinkedList<K,T>
{…}
10. 保持严格的缩进
  a) 使用3个空格缩进
  b) 不要使用tab键或者不标准的缩进比如1、2或者4个空格.
11. 注释的缩进和注释描述的代码同级
12. 所有的注释要拼写正确,不正确的注释意味开发混乱.
13. 使用描述性的变量名.
  a) 避免一个字符的变量名,例如“i”或者“t”。用“index”或者“temp”代替.
  b) 避免使用匈牙利命名法定义“Public”或者“protected”成员.
  c) 不要缩短单词(例如“num”代替“number”).
14. 所有的成员变量应该在顶部定义,用一个空行把它们和属性或者方法分开。
public class MyClass
{
  int m_Number;
  string m_Name;
 
  public void SomeMethod1(){}
  public void SomeMethod2(){}
}
15. 定义局部变量尽量靠近第一次使用的地方。
16. 使用有意思的命名空间,例如产品名、公司名等等
17. 避免使用类型的全称,用“using”声明代替.
18. 避免把“using”声明放在命名空间内.
19. 所有框架的命名空间在前面,自定义或者第三方的命名空间放在后面进行分组.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using MyCompmnay;
using MyControls;
20. 文件名应该反映它包含的类.
21. 总是把“{”放在新的一行.
22. 用匿名方法模拟正常方法的代码结构,排列匿名的代理
(With anonymous methods mimic the code layout of a regular method,
aligned with the anonymous delegate declaration.
a) Comply with placing an open curly brace in a new line)





2 Coding Practices
1. 使用C#预定义的类型胜于系统空间的别名

例如:
object 而不是 Object
string 而不是 String
int 而不是 Int32
2.避免多个类放在一个文件中.
3. 一个文件应该属于一个命名空间而不是多个.
4. 避免一个文件超过500行(不包括自动产生的代码).
5. 避免方法超过25行.
6. 一行不超过80个字符.
7. 不要改动自动产生的代码.
- 5 -
©2003 IDesign Inc. All rights reserved
8. If modifying machine generated code, modify the format and style to match this
coding standard.
a) Use partial classes if possible.
9. Avoid comments that explain the obvious.
10. Code should be self explanatory. Good code with readable variable and method
names should not require comments.
11. Document only operational assumptions, algorithm insights etc.
12. Avoid method-level documentation.
a) Use extensive external documentation for API documentation.
b) Use method-level comments only as tool tips for other developers.
13. Never hard-code a numeric value, always declare a constant instead.
14. Assert every assumption.
15. On average, every fifth line is an assertion.
using System.Diagnostics;
object GetObject()
{…}
object obj = GetObject();
Debug.Assert(obj != null);
16. Make only the most necessary types public, mark others as internal.
17. Always use zero-based arrays.
18. Avoid providing explicit values for enums.
19. Avoid specifying a type for an enum (like long).
20. Never use goto unless in a switch statement fall-through.
www.idesign.net August 2003
- 6 -
©2003 IDesign Inc. All rights reserved
21. Avoid function calls in Boolean conditional statements. Assign into local variables
and check on them:
bool IsEverythingOK()
{…}
//Avoid:
if(IsEverythingOK())
{…}
//Instead:
bool ok = IsEverythingOK();
if(ok)
{…}
22. Always explicitly initialize an array of reference types using a for loop.
public class MyClass
{}
MyClass[] array = new MyClass[100];
for(int index = 0; index < array.Length; index++)
{
array[index] = new MyClass();
}
23. Only catch exceptions for which you have explicit handling.
24. In a catch statement that throws an exception, always throw the original exception to
maintain stack location of original error.
catch(Exception exception)
{
MessageBox.Show(exception.Message);
throw; //Same as throw exception;
}
25. Avoid error code as methods return values.
26. Do not use the new inheritance qualifier. Use override instead.
27. Minimize code in application assemblies (EXE client assemblies), use class libraries
instead to contain business logic.
28. Never hardcode strings that will be presented to end users. Use resources instead.
29. Never hardcode strings that might change based on deployment such as connection
strings.
30. Never use unsafe code unless when using interop.
31. Always use interfaces.
a) See Chapters 1 and 3 in Programming .NET Components.
32. Avoid multiple Main() methods in a single assembly.
www.idesign.net August 2003
- 7 -
©2003 IDesign Inc. All rights reserved
33. Avoid explicit casting. Use the as operator to defensively cast to a type.
Dog dog = new GermanShepherd();
GermanShepherd shepherd = dog as GermanShepherd;
if(shepherd != null)
{…}
34. Never assume a type supports an interface. Defensively query for that interface.
SomeType obj1;
IMyInterface obj2;
/* Some code to initialize obj1, then: */
obj2 = obj1 as IMyInterface;
if(obj2 != null)
{
obj2.Method1();
}
else
{
//Handle error in expected interface
}
35. Do not provide public or protected member variables. Use properties instead.
36. Do not provide public event member variables. Use event accessors instead.
public class MySource
{
MyDelegate m_NumberChangedEvent;
public event MyDelegate NumberChangedEvent
{
add
{
m_NumberChangedEvent += value;
}
remove
{
m_NumberChangedEvent -= value;
}
}
}
37. Classes and interfaces should have at least 2:1 ratio of methods to properties.
38. Avoid interfaces with one member.
39. Strive to have 3-5 members per interface.
40. No more than 20 members per interface.
a) 12 is probably a practical limit.
41. Avoid events as interface members.
42. Avoid abstract methods, use interfaces instead.
43. Always prefer using C# generics in data structures.
44. Expose interfaces on class hierarchies.
a) See Chapter 3 in Programming .NET Components.
www.idesign.net August 2003
- 8 -
©2003 IDesign Inc. All rights reserved
45. Prefer using explicit interface implementation.
a) See Chapter 3 in Programming .NET Components.
46. Always mark public and protected methods as virtual in a non sealed class.
47. When building a long string, use StringBuilder, not string.
48. Always use a curly brace scope in an if statement, even if it conditions a single
statement.
49. With delegates as class members:
a) Copy a delegate to a local variable before publishing to avoid concurrency race
condition.
b) Always check a delegate for null before invoking it.
public class MySource
{
public event EventHandler MyEvent;
public void FireEvent()
{
EventHandler temp = MyEvent;
if(temp != null)
{
temp(this,EventArgs.Empty);
}
}
}
50. Always have a default case in a switch statement that asserts
int number = SomeMethod();
switch(number)
{
case 1:
Trace.WriteLine("Case 1:");
break;
case 2:
Trace.WriteLine("Case 2:");
break;
default:
Debug.Assert(false);
break;
}
51. Avoid providing methods on structures.
a) Parameterized constructors are encouraged.
b) Can overload operators.
52. Always provide a static constructor when providing static member variables.
53. Every line of code should be walked through in a “white box” testing manner.
54. Avoid code that relies on an assembly running from a particular location.
55. Do not use late-binding invocation when early-binding is possible.
www.idesign.net August 2003
- 9 -
©2003 IDesign Inc. All rights reserved
56. Avoid using the trinary conditional operator.
57. Do not use the this reference unless invoking another constructor from within a
constructor.
//Example of proper use of ’this’
public class MyClass
{
public MyClass(string message)
{}
public MyClass() : this("hello")
{}
}
58. Use the EventsHelper class defined in Programming .NET Components to
publish events defensively.
59. Use application logging and tracing.
60. Do not use the base word to access base class members unless you wish to resolve
a conflict with a subclasses member of the same name or when invoking a base class
constructor.
//Example of proper use of ’base’
public class Dog
{
public Dog(string name)
{}
virtual public void Bark(int howLong)
{}
}
public class GermanShepherd : Dog
{
public GermanShepherd(string name): base(name)
{}
override public void Bark(int howLong)
{
base.Bark(howLong);
}
}
61. Implement Dispose() and Finalize() methods based on the template in
Chapter 4 of Programming .NET Components.
62. Avoid casting to and from System.Object in code that uses generics.
63. Use the const directive only on natural constants such as the number of days of
week. Avoid using const on read only variables. For that, use the readonly
directive.
public class MyClass
{
public readonly int Number;
public MyClass(int someValue)
{
Number = someValue;
}
const int DaysInWeek = 7;
}
www.idesign.net August 2003
3 Project Settings and Project Structure
1. Always build your project with warning level 4


2. Treat warning as errors in Release build (note that this is not the default of VS.NET).
a) Although it is optional, this standard recommend treating warnings as errors in
debug builds as well.

3. Never suppress specific compiler warnings.

- 11 -
©2003 IDesign Inc. All rights reserved
4. Always explicitly state your supported runtime versions in the application
configuration file. See Chapter 5 in Programming .NET Components.
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.0.0"/>
<supportedRuntime version="v1.1.5000.0"/>
</startup>
</configuration>
5. Avoid explicit custom version redirection and binding to CLR assemblies.
6. Avoid explicit preprocessor definitions (#define). Use the project settings for
defining conditional compilation constants.
7. Do not put any logic inside AssemblyInfo.cs.
8. Do not put any assembly attributes in any file besides AssemblyInfo.cs.
9. Populate all fields in AssemblyInfo.cs such as company name, description, copyright
notice.
10. All assembly references should use relative path.
11. Disallow cyclic references between assemblies.
12. Avoid multi-module assemblies.
www.idesign.net August 2003
13. Always run code unchecked by default (for performance sake), but explic itly in
checked mode for prone operations.

- 12 -
©2003 IDesign Inc. All rights reserved
int CalcPower(int number,int power)
{
int result = 1;
for(int count = 1;count <= power;count++)
{
checked
{
result *= number;
}
}
return result;
}
14. Avoid tampering with exception handling using the Exception window
(Debug|Exceptions).
15. Strive to uniform version numbers on all assemblies and clients in same logical
application (typically a solution).
16. Name your VS.NET application configuration file as App.Config, and include it in
the project.
17. Avoid explicit code exclusion of method calls (#if…#endif). Use conditional
methods instead.
public class MyClass
{
[Conditional("MySpecialCondition")]
public void MyMethod()
{}
}
www.idesign.net August 2003
18. Modify VS.NET default project structure to your project standard layout, and apply
uniform structure for project folders and files.
19. Link all solution-wide information to a global shared file:


- 13 -
©2003 IDesign Inc. All rights reserved
20. Insert spaces for tabs. Use 3 spaces instead of tabs

a) Tools|Options|Text Editor|C#|Tabs
www.idesign.net August 2003
- 14 -
©2003 IDesign Inc. All rights reserved
21. Release build should contain debug symbols.

22. Always sign your assemblies, including the client applications.
23. Always sign interop assemblies with the project’s SNK file

www.idesign.net August 2003
- 15 -
©2003 IDesign Inc. All rights reserved
4 Framework Specific Guidelines
4.1 Data Access
1. Always use type-safe data sets. Avoid raw ADO.NET.
2. Always use transactions when accessing a database.
3. Always use transaction isolation level set to Serializable.
a) Requires management decision to use anything else.
4. Do not use the Server Explorer to drop connections on windows forms, ASP.NET
forms or web services. Doing so couples the presentation tier to the data tier.
5. Avoid SQL Server authentication.
a) Use Windows authentication instead.
6. Run components accessing SQL Server under separate identity from that of the
calling client.
7. Always warp your stored procedures in a high level, type safe class. Only that class
invokes the stored procedures.
8. Avoid putting any logic inside a stored procedure.
a) If there is an IF inside a stored procedure, you are doing something wrong.
4.2 ASP.NET and Web Services
1. Avoid putting code in ASPX files of ASP.NET. All code should be in the codebehind
class.
2. Code in code behind class of ASP.NET should call other components rather than
contain direct busines s logic.
3. In both ASP.NET pages and web services, wrap a session variables in a local
property. Only that property is allowed to access the session variable, and the rest of
the code uses the property, not the session variable.
4. Avoid setting to True the Auto-Postback property of server controls in ASP.NET.
5. In transactional pages or web services, always store session in SQL server.
6. Turn on Smart Navigation for ASP.NET pages.
7. Strive to provide interfaces for web services
a) See Appendix A of Programming .NET Comp onents.
8. Always provide namespace and service description for web services.
9. Always provide a description for web methods.
10. When adding a web service reference, provide meaningful name for the location.
11. Always modify client-side web service wrapper class to support cookies.
a) You have no way of knowing whether the service uses Session state or not.
www.idesign.net August 2003
- 16 -
©2003 IDesign Inc. All rights reserved
4.3 Serialization
1. Always mark non-sealed classes as Serializable.
2. Always mark un-serializable member variables as non serializable.
3. Always mark delegates on a serialized class as non-serializable.
[Serializable]
public class MyClass
{
[field:NonSerialized]
public event MyDelegate Delegate;
}
4.4 Multithreading
1. Use Synchronization Domains. See Chapter 8 in Programming .NET Components.
a) Avoid manual synchronization, because they often lead to deadlocks and race
conditions.
2. Never call outside your synchronization domain.
3. Manage asynchronous call completion on a callback method.
a) Do not wait, poll, or block for completion.
4. Always name your threads.
a) Name is traces in the debugger Threads window, making a debug session more
productive.
Thread currentThread = Thread.CurrentThread;
string threadName = "Main UI Thread";
currentThread.Name = threadName;
5. Do not call Suspend() or Resume() on a thread.
6. Do not call Thread.Sleep().
a) Thread.Sleep(0) is acceptable optimization technique to force a context
switch.
b) Thread.Sleep() is acceptable in testing or simulation code.
7. Do not call Thread.SpinWait().
8. Do not call Thread.Abort() to terminate threads.
a) Use a synchronization object instead to signal the thread to terminate. See
Chapter 8 in Programming .NET Components.
9. Avoid explicitly setting thread priority to control execution.
a) Can set thread priority based on task semantic, such as bellow normal for a
screen saver.
10. Do not read the value of the thread state property.
a) Use Thread.IsAlive() to determine whether the thread is dead.
11. Do not rely on setting the thread type to background thread for application shutdown.
a) Use a watchdog or other monitoring entity to deterministically kill threads.
12. Do not use thread local storage unless thread affinity is guaranteed.
www.idesign.net August 2003
- 17 -
©2003 IDesign Inc. All rights reserved
13. Never call Thread.Join() without checking that you are not joining your own
thread.
void WaitForThreadToDie(Thread thread)
{
Debug.Assert(Thread.CurrentThread.GetHashCode() != tread.GetHashCode());
thread.Join();
}
14. Always use the lock() statement rather than explicit Monitor manipulation.
15. Always encapsulate the lock() statement inside the object it protects.
public class MyClass
{
public void DoSomething()
{
lock(this)
{
//Do Something
}
}
}
a) Can use synchronized methods instead of writing the lock() statement
yourself.
16. Avoid fragmented locking (see Chapter 8 of Programming .NET Components).
17. Avoid using a Monitor to wait or pulse objects. Use manual or auto-reset events
instead.
18. Always release a Mutex inside a finally statement to handle exceptions.
19. Do not use volatile variables. Lock your object or fields instead to guarantee
deterministic and thread-safe access.
4.5 Remoting
1. Prefer administrative configuration to programmatic configuration.
2. Always implement IDisposable on a single call objects.
3. Always prefer TCP channel and binary format when using remoting.
a) Unless a firewall is present.
4. Always provide a null lease for a singleton object.
public class MySingleton : MarshalByRefObject
{
public override object InitializeLifetimeService()
{
return null;
}
}
5. always provide a sponsor for a client activated object. Sponsor should return initial
lease timed.
a) See Chapter 10 of Programming .NET Components.
www.idesign.net August 2003
- 18 -
©2003 IDesign Inc. All rights reserved
6. Always unregister a sponsor on client application shutdown.
7. Always put remote objects in class libraries.
8. Avoid using SoapSuds.
9. Avoid hosting in IIS.
10. Avoid using uni-directional channels.
11. Always load a remoting configuration file in Main() even if the file is empty, and
the application does not use remoting.
a) Allow the option of remoting some types later on post deployment, and
changing the application topology.
static void Main()
{
RemotingConfiguration.Configure("MyApp.exe.config");
/* Rest of Main() */
}
12. Avoid using Activator.GetObject() and
Activator.CreateiInstance() for remote objects activation. Use new
instead.
13. Always register port 0 on the client side, to allow callbacks.
14. Always elevate type filtering to full on both client and host to allow callbacks.
Host Config file:
<channels>
<channel ref="tcp" port="8005">
<serverProviders>
<formatter ref="soap" typeFilterLevel="Full"/>
<formatter ref="binary" typeFilterLevel="Full"/>
</serverProviders>
</channel>
<channel ref="http" port="8006">
<serverProviders>
<formatter ref="soap" typeFilterLevel="Full"/>
<formatter ref="binary" typeFilterLevel="Full"/>
</serverProviders>
</channel>
</channels>
Client Config file:
<channels>
<channel ref="tcp" port="0">
<serverProviders>
<formatter ref="soap" typeFilterLevel="Full"/>
<formatter ref="binary" typeFilterLevel="Full"/>
</serverProviders>
</channel>
</channels>
www.idesign.net August 2003
- 19 -
©2003 IDesign Inc. All rights reserved
4.6 Security
1. Always demand your own strong name on assemblies and components that are
private to the application, but are public (so that only you can use them).
public class PublicKeys
{
public const string MyCompany = "1234567894800000940000000602000000240000"+
"52534131000400000100010007D1FA57C4AED9F0"+
"A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C83"+
"4C99921EB23BE79AD9D5DCC1DD9AD23613210290"+
"0B723CF980957FC4E177108FC607774F29E8320E"+
"92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99"+
"285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF"+
"0FC4963D261C8A12436518206DC093344D5AD293";
}
[StrongNameIdentityPermission(SecurityAction.LinkDemand,
PublicKey = PublicKeys.MyCompany)]
public class MyClass
{…}
2. Apply encryption and security protection on application configuration files.
3. Assert unmanaged code permission, and demand appropriate permission instead.
4. On server machines deploy code-access security policy that grants only Microsoft,
ECMA and self (identified by strong name) full trust.
a) All other code is implicitly granted nothing.
5. On client machine, deploy a security policy which grants client application only the
permissions to call back the server and to potentially display user interface.
a) Client application identified by strong name.
6. Always refuse at the assembly level all permissions not required to perform task at
hand.
a) The counter a luring attack.
[assembly:UIPermission(SecurityAction.RequestRefuse,
Window=UIPermissionWindow.AllWindows)]
7. Always set the principal policy in every Main() method to Windows
public class MyClass
{
static void Main()
{
AppDomain currentDomain = Thread.GetDomain();
currentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
}
//other methods
}
8. Never assert a permission without demanding a different permission in its place. See
Chapter 12 in Programming .NET Components.
www.idesign.net August 2003
4.7 Enterprise Services
1. Do not catch exceptions in a transactional method. Use the AutoComplete
attribute.
a) See COM and .NET Component Services.
2. Do not call SetComplete(), SetAbort(), and the like. Use the
AutoComplete attribute.
[Transaction]
public class MyComponent : ServicedComponent
{
[AutoComplete]
public void MyMethod(long objectIdentifier)
{
GetState(objectIdentifier);
DoWork();
SaveState(objectIdentifier);
}
}
3. Always override CanBePooled and return true (unless you have a good reason
not to return to pool)
public class MyComponent :ServicedComponent
{
protected override bool CanBePooled()
{
return true;
}
}
4. Always call Dispose() explicitly on a pooled objects unless the component is
configured to use JITA as well.
5. Set authentication level to privacy on all applications.
6. Use Enterprise Services whenever more than one object or more than one database is
involved in a single transaction.
7. Set impersonation level on client assemblies to Identity.
8. Always set ComponentAccessControl attribute on serviced components to true
a) The default is True
9. Always add to the Marshaler role the Everyone user
[assembly: SecurityRole("Marshaler",SetEveryoneAccess = true)]
10. Apply SecureMethod attribute to all classes requiring authentication.

您可能感兴趣的与本文相关的镜像

PyTorch 2.6

PyTorch 2.6

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

目录 1. 简介 1 1.1 Hello world 1 1.2 程序结构 2 1.3 类型和变量 3 1.4 表达式 6 1.5 语句 8 1.6 类和对象 12 1.6.1 成员 12 1.6.2 可访问性 13 1.6.3 类型参数 13 1.6.4 基类 14 1.6.5 字段 14 1.6.6 方法 15 1.6.6.1 参数 15 1.6.6.2 方法体和局部变量 17 1.6.6.3 静态方法和实例方法 17 1.6.6.4 虚方法、重写方法和抽象方法 18 1.6.6.5 方法重载 20 1.6.7 其他函数成员 21 1.6.7.1 构造函数 22 1.6.7.2 属性 23 1.6.7.3 索引器 23 1.6.7.4 事件 23 1.6.7.5 运算符 24 1.6.7.6 析构函数 25 1.7 结构 25 1.8 数组 26 1.9 接口 27 1.10 枚举 28 1.11 委托 29 1.12 特性 30 2. 词法结构 33 2.1 程序 33 2.2 文法 33 2.2.1 文法表示法 33 2.2.2 词法文法 34 2.2.3 句法文法 34 2.3 词法分析 34 2.3.1 行结束符 35 2.3.2 注释 35 2.3.3 空白 36 2.4 标记 37 2.4.1 Unicode 字符转义序列 37 2.4.2 标识符 38 2.4.3 关键字 39 2.4.4 文本 41 2.4.4.1 布尔值 41 2.4.4.2 整数 41 2.4.4.3 实数 42 2.4.4.4 字符 43 2.4.4.5 字符串 44 2.4.4.6 null 文本 46 2.4.5 运算符和标点符号 46 2.5 预处理指令 46 2.5.1 条件编译符号 47 2.5.2 预处理表达式 48 2.5.3 声明指令 49 2.5.4 条件编译指令 49 2.5.5 诊断指令 52 2.5.6 区域指令 52 2.5.7 行指令 53 2.5.8 Pragma 指令 53 2.5.8.1 Pragma warning 54 3. 基本概念 55 3.1 应用程序启动 55 3.2 应用程序终止 56 3.3 声明 56 3.4 成员 58 3.4.1 命名空间成员 58 3.4.2 结构成员 59 3.4.3 枚举成员 59 3.4.4 类成员 59 3.4.5 接口成员 59 3.4.6 数组成员 60 3.4.7 委托成员 60 3.5 成员访问 60 3.5.1 已声明可访问性 60 3.5.2 可访问域 61 3.5.3 实例成员的受保护访问 63 3.5.4 可访问性约束 64 3.6 签名和重载 65 3.7 范围 66 3.7.1 名称隐藏 68 3.7.1.1 通过嵌套隐藏 68 3.7.1.2 通过继承隐藏 69 3.8 命名空间和类型名称 70 3.8.1 完全限定名 72 3.9 自动内存管理 73 3.10 执行顺序 75 4. 类型 77 4.1 值类型 77 4.1.1 System.ValueType 类型 78 4.1.2 默认构造函数 78 4.1.3 结构类型 79 4.1.4 简单类型 79 4.1.5 整型 80 4.1.6 浮点型 81 4.1.7 decimal 类型 82 4.1.8 bool 类型 82 4.1.9 枚举类型 82 4.1.10 可以为 null 的类型 83 4.2 引用类型 83 4.2.1 类类型 84 4.2.2 对象类型 84 4.2.3 dynamic 类型 84 4.2.4 string 类型 85 4.2.5 接口类型 85 4.2.6 数组类型 85 4.2.7 委托类型 85 4.3 装箱和拆箱 85 4.3.1 装箱转换 85 4.3.2 拆箱转换 87 4.4 构造类型 87 4.4.1 类型实参 88 4.4.2 开放和封闭类型 88 4.4.3 绑定和未绑定类型 89 4.4.4 满足约束 89 4.5 类型形参 90 4.6 表达式树类型 91 4.7 dynamic 类型 91 5. 变量 93 5.1 变量类别 93 5.1.1 静态变量 93 5.1.2 实例变量 93 5.1.2.1 类中的实例变量 93 5.1.2.2 结构中的实例变量 94 5.1.3 数组元素 94 5.1.4 值参数 94 5.1.5 引用形参 94 5.1.6 输出形参 94 5.1.7 局部变量 95 5.2 默认值 95 5.3 明确赋值 96 5.3.1 初始已赋值变量 96 5.3.2 初始未赋值变量 97 5.3.3 确定明确赋值的细则 97 5.3.3.1 一般语句规则 98 5.3.3.2 块语句、checked 和 unchecked 语句 98 5.3.3.3 表达式语句 98 5.3.3.4 声明语句 98 5.3.3.5 if 语句 98 5.3.3.6 switch 语句 99 5.3.3.7 while 语句 99 5.3.3.8 do 语句 99 5.3.3.9 for 语句 99 5.3.3.10 break、continue 和 goto 语句 100 5.3.3.11 throw 语句 100 5.3.3.12 return 语句 100 5.3.3.13 try-catch 语句 100 5.3.3.14 try-finally 语句 100 5.3.3.15 try-catch-finally 语句 101 5.3.3.16 foreach 语句 102 5.3.3.17 using 语句 102 5.3.3.18 lock 语句 102 5.3.3.19 yield 语句 102 5.3.3.20 简单表达式的一般规则 102 5.3.3.21 带有嵌入表达式的表达式的一般规则 103 5.3.3.22 调用表达式和对象创建表达式 103 5.3.3.23 简单赋值表达式 103 5.3.3.24 && 表达式 104 5.3.3.25 || 表达式 104 5.3.3.26 ! 表达式 105 5.3.3.27 ?? 表达式 106 5.3.3.28 ?: 表达式 106 5.3.3.29 匿名函数 106 5.4 变量引用 107 5.5 变量引用的原子性 107 6. 转换 109 6.1 隐式转换 109 6.1.1 标识转换 110 6.1.2 隐式数值转换 110 6.1.3 隐式枚举转换 110 6.1.4 可以为 null 的隐式转换 110 6.1.5 null 文本转换 111 6.1.6 隐式引用转换 111 6.1.7 装箱转换 111 6.1.8 隐式动态转换 112 6.1.9 隐式常量表达式转换 112 6.1.10 涉及类型形参的隐式转换 112 6.1.11 用户定义的隐式转换 113 6.1.12 匿名函数转换和方法组转换 113 6.2 显式转换 113 6.2.1 显式数值转换 114 6.2.2 显式枚举转换 115 6.2.3 可以为 null 的显式转换 115 6.2.4 显式引用转换 116 6.2.5 拆箱转换 117 6.2.6 显式动态转换 117 6.2.7 涉及类型形参的显式转换 118 6.2.8 用户定义的显式转换 118 6.3 标准转换 119 6.3.1 标准隐式转换 119 6.3.2 标准显式转换 119 6.4 用户定义的转换 119 6.4.1 允许的用户定义转换 119 6.4.2 提升转换运算符 119 6.4.3 用户定义转换的计算 120 6.4.4 用户定义的隐式转换 120 6.4.5 用户定义的显式转换 121 6.5 匿名函数转换 122 6.5.1 匿名函数转换为委托类型的计算 123 6.5.2 匿名函数转换为表达式树类型的计算 124 6.5.3 实现示例 124 6.6 方法组转换 126 7. 表达式 129 7.1 表达式的分类 129 7.1.1 表达式的值 130 7.2 静态和动态绑定 130 7.2.1 绑定时间 131 7.2.2 动态绑定 131 7.2.3 构成表达式的类型 131 7.3 运算符 131 7.3.1 运算符的优先级和顺序关联性 132 7.3.2 运算符重载 133 7.3.3 一元运算符重载决策 134 7.3.4 二元运算符重载决策 134 7.3.5 候选用户定义运算符 134 7.3.6 数值提升 135 7.3.6.1 一元数值提升 135 7.3.6.2 二元数值提升 135 7.3.7 提升运算符 136 7.4 成员查找 137 7.4.1 基类型 138 7.5 函数成员 138 7.5.1 实参列表 140 7.5.1.1 对应形参 141 7.5.1.2 实参列表的运行时计算 142 7.5.2 类型推断 143 7.5.2.1 第一阶段 144 7.5.2.2 第二阶段 144 7.5.2.3 输入类型 144 7.5.2.4 输出类型 145 7.5.2.5 依赖 145 7.5.2.6 输出类型推断 145 7.5.2.7 参数类型显式推断 145 7.5.2.8 精确推断 145 7.5.2.9 下限推断 145 7.5.2.10 上限推断 146 7.5.2.11 固定 147 7.5.2.12 推断返回类型 147 7.5.2.13 方法组转换的类型推断 148 7.5.2.14 查找一组表达式的最通用类型 148 7.5.3 重载决策 149 7.5.3.1 适用函数成员 149 7.5.3.2 更好的函数成员 150 7.5.3.3 表达式的更佳转换 151 7.5.3.4 类型的更佳转换 151 7.5.3.5 更佳转换目标 151 7.5.3.6 泛型类中的重载 151 7.5.4 动态重载决策的编译时检查 152 7.5.5 函数成员调用 152 7.5.5.1 已装箱实例上的调用 153 7.6 基本表达式 154 7.6.1 文本 154 7.6.2 简单名称 154 7.6.2.1 块中的固定含义 155 7.6.3 带括号的表达式 156 7.6.4 成员访问 157 7.6.4.1 相同的简单名称和类型名称 158 7.6.4.2 语法多义性 159 7.6.5 调用表达式 159 7.6.5.1 方法调用 160 7.6.5.2 扩展方法调用 161 7.6.5.3 委托调用 163 7.6.6 元素访问 164 7.6.6.1 数组访问 164 7.6.6.2 索引器访问 165 7.6.7 this 访问 165 7.6.8 基访问 166 7.6.9 后缀增量和后缀减量运算符 166 7.6.10 new 运算符 167 7.6.10.1 对象创建表达式 168 7.6.10.2 对象初始值设定项 169 7.6.10.3 集合初始值设定项 171 7.6.10.4 数组创建表达式 172 7.6.10.5 委托创建表达式 174 7.6.10.6 匿名对象创建表达式 175 7.6.11 typeof 运算符 177 7.6.12 checked 和 unchecked 运算符 178 7.6.13 默认值表达式 180 7.6.14 匿名方法表达式 181 7.7 一元运算符 181 7.7.1 一元加运算符 181 7.7.2 一元减运算符 181 7.7.3 逻辑否定运算符 182 7.7.4 按位求补运算符 182 7.7.5 前缀增量和减量运算符 182 7.7.6 强制转换表达式 183 7.8 算术运算符 184 7.8.1 乘法运算符 184 7.8.2 除法运算符 185 7.8.3 余数运算符 186 7.8.4 加法运算符 187 7.8.5 减法运算符 189 7.9 移位运算符 190 7.10 关系和类型测试运算符 192 7.10.1 整数比较运算符 192 7.10.2 浮点比较运算符 193 7.10.3 小数比较运算符 194 7.10.4 布尔相等运算符 194 7.10.5 枚举比较运算符 194 7.10.6 引用类型相等运算符 194 7.10.7 字符串相等运算符 196 7.10.8 委托相等运算符 196 7.10.9 相等运算符和 null 197 7.10.10 is 运算符 197 7.10.11 as 运算符 197 7.11 逻辑运算符 198 7.11.1 整数逻辑运算符 199 7.11.2 枚举逻辑运算符 199 7.11.3 布尔逻辑运算符 199 7.11.4 可以为 null 的布尔逻辑运算符 199 7.12 条件逻辑运算符 200 7.12.1 布尔条件逻辑运算符 200 7.12.2 用户定义的条件逻辑运算符 201 7.13 空合并运算符 201 7.14 条件运算符 202 7.15 匿名函数表达式 203 7.15.1 匿名函数签名 204 7.15.2 匿名函数体 205 7.15.3 重载决策 205 7.15.4 匿名函数与动态绑定 206 7.15.5 外层变量 206 7.15.5.1 捕获的外层变量 206 7.15.5.2 局部变量实例化 207 7.15.6 匿名函数表达式计算 209 7.16 查询表达式 209 7.16.1 查询表达式的多义性 210 7.16.2 查询表达式转换 210 7.16.2.1 带继续符的 select 和 groupby 子句 211 7.16.2.2 显式范围变量类型 211 7.16.2.3 退化查询表达式 212 7.16.2.4 from、let、where、join 和 orderby 子句 212 7.16.2.5 select 子句 216 7.16.2.6 Groupby 子句 216 7.16.2.7 透明标识符 216 7.16.3 查询表达式模式 218 7.17 赋值运算符 219 7.17.1 简单赋值 219 7.17.2 复合赋值 221 7.17.3 事件赋值 222 7.18 表达式 222 7.19 常量表达式 223 7.20 布尔表达式 224 8. 语句 225 8.1 结束点和可到达性 225 8.2 块 227 8.2.1 语句列表 227 8.3 空语句 228 8.4 标记语句 228 8.5 声明语句 229 8.5.1 局部变量声明 229 8.5.2 局部常量声明 230 8.6 表达式语句 231 8.7 选择语句 231 8.7.1 if 语句 231 8.7.2 switch 语句 232 8.8 迭代语句 236 8.8.1 while 语句 236 8.8.2 do 语句 236 8.8.3 for 语句 237 8.8.4 foreach 语句 238 8.9 跳转语句 240 8.9.1 break 语句 241 8.9.2 continue 语句 242 8.9.3 goto 语句 242 8.9.4 return 语句 243 8.9.5 throw 语句 244 8.10 try 语句 245 8.11 checked 语句和 unchecked 语句 247 8.12 lock 语句 248 8.13 using 语句 248 8.14 yield 语句 250 9. 命名空间 253 9.1 编译单元 253 9.2 命名空间声明 253 9.3 Extern 别名 254 9.4 using 指令 255 9.4.1 using 别名指令 256 9.4.2 Using 命名空间指令 258 9.5 命名空间成员 260 9.6 类型声明 260 9.7 命名空间别名限定符 261 9.7.1 别名的唯一性 262 10. 类 263 10.1 类声明 263 10.1.1 类修饰符 263 10.1.1.1 抽象类 264 10.1.1.2 密封类 264 10.1.1.3 静态类 264 10.1.2 分部修饰符 265 10.1.3 类型形参 265 10.1.4 类基本规范 266 10.1.4.1 基类 266 10.1.4.2 接口实现 267 10.1.5 类型形参约束 268 10.1.6 类体 272 10.2 分部类型 272 10.2.1 特性 272 10.2.2 修饰符 273 10.2.3 类型形参和约束 273 10.2.4 基类 273 10.2.5 基接口 274 10.2.6 成员 274 10.2.7 分部方法 275 10.2.8 名称绑定 277 10.3 类成员 277 10.3.1 实例类型 278 10.3.2 构造类型的成员 279 10.3.3 继承 280 10.3.4 new 修饰符 280 10.3.5 访问修饰符 281 10.3.6 构成类型 281 10.3.7 静态成员和实例成员 281 10.3.8 嵌套类型 282 10.3.8.1 完全限定名 282 10.3.8.2 已声明可访问性 282 10.3.8.3 隐藏 283 10.3.8.4 this 访问 283 10.3.8.5 对包含类型的私有和受保护成员的访问 284 10.3.8.6 泛型类中的嵌套类型 285 10.3.9 保留成员名称 286 10.3.9.1 为属性保留的成员名称 286 10.3.9.2 为事件保留的成员名称 287 10.3.9.3 为索引器保留的成员名称 287 10.3.9.4 为析构函数保留的成员名称 287 10.4 常量 287 10.5 字段 289 10.5.1 静态字段和实例字段 290 10.5.2 只读字段 291 10.5.2.1 对常量使用静态只读字段 291 10.5.2.2 常量和静态只读字段的版本控制 291 10.5.3 可变字段 292 10.5.4 字段初始化 293 10.5.5 变量初始值设定项 293 10.5.5.1 静态字段初始化 294 10.5.5.2 实例字段初始化 295 10.6 方法 296 10.6.1 方法形参 298 10.6.1.1 值参数 299 10.6.1.2 引用形参 299 10.6.1.3 输出形参 300 10.6.1.4 形参数组 301 10.6.2 静态方法和实例方法 303 10.6.3 虚方法 304 10.6.4 重写方法 305 10.6.5 密封方法 307 10.6.6 抽象方法 308 10.6.7 外部方法 309 10.6.8 分部方法 310 10.6.9 扩展方法 310 10.6.10 方法体 311 10.6.11 方法重载 311 10.7 属性 311 10.7.1 静态属性和实例属性 312 10.7.2 访问器 313 10.7.3 自动实现的属性 317 10.7.4 可访问性 318 10.7.5 虚、密封、重写和抽象访问器 319 10.8 事件 321 10.8.1 类似字段的事件 323 10.8.2 事件访问器 324 10.8.3 静态事件和实例事件 325 10.8.4 虚、密封、重写和抽象访问器 325 10.9 索引器 326 10.9.1 索引器重载 329 10.10 运算符 329 10.10.1 一元运算符 331 10.10.2 二元运算符 331 10.10.3 转换运算符 332 10.11 实例构造函数 334 10.11.1 构造函数初始值设定项 335 10.11.2 实例变量初始值设定项 336 10.11.3 构造函数执行 336 10.11.4 默认构造函数 338 10.11.5 私有构造函数 338 10.11.6 可选的实例构造函数形参 339 10.12 静态构造函数 339 10.13 析构函数 341 10.14 迭代器 343 10.14.1 枚举器接口 343 10.14.2 可枚举接口 343 10.14.3 产生类型 343 10.14.4 枚举器对象 343 10.14.4.1 MoveNext 方法 344 10.14.4.2 Current 属性 345 10.14.4.3 Dispose 方法 345 10.14.5 可枚举对象 345 10.14.5.1 GetEnumerator 方法 346 10.14.6 实现示例 346 11. 结构 353 11.1 结构声明 353 11.1.1 结构修饰符 353 11.1.2 分部修饰符 353 11.1.3 结构接口 354 11.1.4 结构体 354 11.2 结构成员 354 11.3 类和结构的区别 354 11.3.1 值语义 355 11.3.2 继承 355 11.3.3 赋值 356 11.3.4 默认值 356 11.3.5 装箱和拆箱 356 11.3.6 this 的含义 358 11.3.7 字段初始值设定项 358 11.3.8 构造函数 358 11.3.9 析构函数 359 11.3.10 静态构造函数 359 11.4 结构示例 360 11.4.1 数据库整数类型 360 11.4.2 数据库布尔类型 361 12. 数组 365 12.1 数组类型 365 12.1.1 System.Array 类型 366 12.1.2 数组和泛型 IList 接口 366 12.2 数组创建 366 12.3 数组元素访问 367 12.4 数组成员 367 12.5 数组协变 367 12.6 数组初始值设定项 367 13. 接口 369 13.1 接口声明 369 13.1.1 接口修饰符 369 13.1.2 分部修饰符 369 13.1.3 Variant 类型形参列表 370 13.1.3.1 变化安全性 370 13.1.3.2 变化转换 371 13.1.4 基接口 371 13.1.5 接口体 372 13.2 接口成员 372 13.2.1 接口方法 373 13.2.2 接口属性 373 13.2.3 接口事件 374 13.2.4 接口索引器 374 13.2.5 接口成员访问 374 13.3 完全限定接口成员名 376 13.4 接口实现 376 13.4.1 显式接口成员实现 377 13.4.2 所实现接口的唯一性 379 13.4.3 泛型方法实现 380 13.4.4 接口映射 381 13.4.5 接口实现继承 383 13.4.6 接口重新实现 385 13.4.7 抽象类和接口 386 14. 枚举 387 14.1 枚举声明 387 14.2 枚举修饰符 387 14.3 枚举成员 388 14.4 System.Enum 类型 390 14.5 枚举值和运算 390 15. 委托 391 15.1 委托声明 391 15.2 委托兼容性 393 15.3 委托实例化 393 15.4 委托调用 394 16. 异常 397 16.1 导致异常的原因 397 16.2 System.Exception 类 397 16.3 异常的处理方式 397 16.4 公共异常类 398 17. 特性 399 17.1 特性类 399 17.1.1 特性用法 399 17.1.2 定位和命名参数 400 17.1.3 特性参数类型 401 17.2 特性说明 401 17.3 特性实例 406 17.3.1 特性的编译 406 17.3.2 特性实例的运行时检索 406 17.4 保留特性 407 17.4.1 AttributeUsage 特性 407 17.4.2 Conditional 特性 408 17.4.2.1 条件方法 408 17.4.2.2 条件特性类 410 17.4.3 Obsolete 特性 411 17.5 互操作的特性 412 17.5.1 与 COM 和 Win32 组件的互操作 412 17.5.2 与其他 .NET 语言的互操作 412 17.5.2.1 IndexerName 特性 412 18. 不安全代码 413 18.1 不安全上下文 413 18.2 指针类型 415 18.3 固定和可移动变量 418 18.4 指针转换 418 18.4.1 指针数组 419 18.5 表达式中的指针 420 18.5.1 指针间接寻址 420 18.5.2 指针成员访问 421 18.5.3 指针元素访问 422 18.5.4 address-of 运算符 422 18.5.5 指针递增和递减 423 18.5.6 指针算术运算 423 18.5.7 指针比较 424 18.5.8 sizeof 运算符 425 18.6 fixed 语句 425 18.7 固定大小缓冲区 429 18.7.1 固定大小缓冲区的声明 429 18.7.2 表达式中的固定大小缓冲区 430 18.7.3 明确赋值检查 431 18.8 堆栈分配 431 18.9 动态内存分配 432 A. 文档注释 435 A.1 简介 435 A.2 建议的标记 436 A.2.1 <c> 437 A.2.2 <code> 437 A.2.3 <example> 437 A.2.4 <exception> 438 A.2.5 <include> 438 A.2.6 <list> 439 A.2.7 <para> 440 A.2.8 <param> 440 A.2.9 <paramref> 441 A.2.10 <permission> 441 A.2.11 <remark> 442 A.2.12 <returns> 442 A.2.13 <see> 442 A.2.14 <seealso> 443 A.2.15 <summary> 443 A.2.16 <value> 444 A.2.17 <typeparam> 444 A.2.18 <typeparamref> 444 A.3 处理文档文件 445 A.3.1 ID 字符串格式 445 A.3.2 ID 字符串示例 446 A.4 示例 449 A.4.1 C# 源代码 449 A.4.2 生成 XML 452 B. 语法 455 B.1 词法文法 455 B.1.1 行结束符 455 B.1.2 注释 455 B.1.3 空白 456 B.1.4 标记 456 B.1.5 Unicode 字符转义序列 456 B.1.6 标识符 456 B.1.7 关键字 458 B.1.8 文本 458 B.1.9 运算符和标点符号 460 B.1.10 预处理指令 460 B.2 句法文法 463 B.2.1 基本概念 463 B.2.2 类型 463 B.2.3 变量 464 B.2.4 表达式 464 B.2.5 语句 471 B.2.6 命名空间 475 B.2.7 类 475 B.2.8 结构 483 B.2.9 数组 483 B.2.10 接口 484 B.2.11 枚举 485 B.2.12 委托 486 B.2.13 特性 486 B.3 不安全代码的语法扩展 487 C. 参考资料 491
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值