1,#region Windows 窗体设计器生成的代码
#endregion
#region / #endregion 折叠用
2,partial class Form1
partial 修饰 类 接口,结构体,表明他们代码太长要放在几个cs文件中完成;cs中没有头文件的概念,要引用就用using namespace xx
简单的说法:[STAThread]指示应用程序的默认线程模型是单线程单元 (STA)。启动线程模型可设置为单线程单元或多线程单元。
3,用using 包含命名空间时,有时会提示不存在包,此时右键工程,可以增加引用。
4,属性:
Attribute作为编译器的指令
在C#中存在着一定数量的编译器指令,如:#define DEBUG, #undefine DEBUG, #if等。这些指令专属于C#,而且在数量上是固定的。而Attribute用作编译器指令则不受数量限制。比如下面的三个Attribute:
Conditional:起条件编译的作用,只有满足条件,才允许编译器对它的代码进行编译。一般在程序调试的时候使用。
DllImport:用来标记非.NET的函数,表明该方法在一个外部的DLL中定义。
Obsolete:这个属性用来标记当前的方法已经被废弃,不再使用了。
下面的代码演示了上述三个属性的使用:
1
#define DEBUG //这里定义条件
2
3
using System;
4
using System.Runtime.InteropServices;
5
using System.Diagnostics;
6
7
namespace AttributeDemo
8
{
9
class MainProgramClass
10
{
11
12
[DllImport("User32.dll")]
13
public static extern int MessageBox(int hParent, string Message, string Caption, int Type);
14
15
static void Main(string[] args)
16
{
17
DisplayRunningMessage();
18
DisplayDebugMessage();
19
20
MessageBox(0,"Hello","Message",0);
21
22
Console.ReadLine();
23
}
24
25
[Conditional("DEBUG")]
26
private static void DisplayRunningMessage()
27
{
28
Console.WriteLine("开始运行Main子程序。当前时间是"+DateTime.Now);
29
}
30
31
[Conditional("DEBUG")]
32
//[Obsolete("Don't use Old method, use New method", true)]
33
[Obsolete]
34
private static void DisplayDebugMessage()
35
{
36
Console.WriteLine("开始Main子程序");
37
}
38
}
39
}
#define DEBUG //这里定义条件2
3
using System;4
using System.Runtime.InteropServices;5
using System.Diagnostics;6
7
namespace AttributeDemo8
{9
class MainProgramClass10
{11
12
[DllImport("User32.dll")]13
public static extern int MessageBox(int hParent, string Message, string Caption, int Type);14
15
static void Main(string[] args)16
{17
DisplayRunningMessage();18
DisplayDebugMessage();19
20
MessageBox(0,"Hello","Message",0);21
22
Console.ReadLine();23
}24
25
[Conditional("DEBUG")]26
private static void DisplayRunningMessage()27
{28
Console.WriteLine("开始运行Main子程序。当前时间是"+DateTime.Now);29
}30
31
[Conditional("DEBUG")]32
//[Obsolete("Don't use Old method, use New method", true)] 33
[Obsolete]34
private static void DisplayDebugMessage()35
{36
Console.WriteLine("开始Main子程序");37
}38
}39
}
本文介绍了C#中的Attribute特性,包括Conditional、DllImport及Obsolete等,并通过示例代码展示了它们的应用场景。此外,还涉及了partial class的使用方法以及解决using命名空间时出现的问题。

418

被折叠的 条评论
为什么被折叠?



