Attribute特性2——丢弃特性ObsoleteAttribute
这个预定义特性标记了不应被使用的程序实体。它可以让您通知编译器丢弃某个特定的目标元素。例如,当一个新方法被用在一个类中,但是您仍然想要保持类中的旧方法,您可以通过显示一个应该使用新方法,而不是旧方法的消息,来把它标记为 obsolete(过时的)。
规定该特性的语法如下:
[Obsolete(
message
)]
[Obsolete(
message,
iserror
)]
其中:
参数 message,是一个字符串,描述项目为什么过时以及该替代使用什么。
参数 iserror,是一个布尔值。如果该值为 true,编译器应把该项目的使用当作一个错误。默认值是 false(编译器生成一个警告)。警告或错误信息即为message。
上代码:
// 特性方法
public static class MyClass
{
#region ObsoleteAttribute
public static void Method1()
{
Console.WriteLine("It is the method1");
}
[Obsolete("My name is warning, please call which new function called method3", false)]
public static void Method2()
{
Console.WriteLine("It is the method2");
}
[Obsolete("My name is error, please call which new function called method3", true)]
public static void Method3()
{
Console.WriteLine("It is the method3");
}
#endregion
}
测试方法1:
static void Main(string[] args)
{
MyClass.Method1();
}
结果1:
报警告,但是可以执行。
测试方法2:
```csharp
static void Main(string[] args)
{
MyClass.Method2();
}
结果2:
无法运行,报错
测试方法3:
static void Main(string[] args)
{
MyClass.Method3();
}
结果3:
正常运行
PS:我是青春代码,山高路远,江湖再见。
友情提示:转载请注明出处。