C#特性 详解

一:Conditional:条件特性,预定义了一个条件方法。
使用方法:
[Conditional("DEBUG")]
public void test()
{
MessageBox.Show("xxxx");
Console.WriteLine("xxxxxxx");
}
上述特性表示:只有处于Debug模式下,才会调用该方法。

二:Obsolete:这个预定义特性标记了不应被使用的程序实体。它可以让您通知编译器丢弃某个特定的目标元素。例如,当一个新方法被用在一个类中,但是您仍然想要保持类中的旧方法,您可以通过显示一个应该使用新方法,而不是旧方法的消息,来把它标记为 obsolete(过时的)。

public class MyClass
{
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]
static void OldMethod()
{
Console.WriteLine("It is the old method");
}
static void NewMethod()
{
Console.WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}
}

三:DllImport:用来标记非.NET的函数,表明该方法在一个外部的DLL中定义。
[DllImport("User32.dll")]
public static extern int MessageBox(int hParent, string Message, string Caption, int Type);

static void Main(string[] args)
{
DisplayRunningMessage();
DisplayDebugMessage();
MessageBox(0,"Hello","Message",0);
Console.ReadLine();
}

猜你喜欢

转载自www.cnblogs.com/LCLBook/p/11857989.html