Attribute is an object that associates with an element in a program.
Attributes: intrinsic and custom.
using System;
class BasicAttributeDemo
{
[Obsolete]
public void MyFirstDeprecatedMethod()
{
Console.WriteLine("Called MyFirstDeprecatedMethod().");
}
[ObsoleteAttribute]
public void MySecondDeprecatedMethod()
{
Console.WriteLine("Called MySecondDeprecatedMethod().");
}
[Obsolete("You shouldn't use this method anymore.")]
public void MyThirdDeprecatedMethod()
{
Console.WriteLine("Called MyThirdDeprecatedMethod().");
}
// make the program thread safe for COM
[STAThread]
static void Main(string[] args)
{
BasicAttributeDemo attrDemo = new BasicAttributeDemo();
attrDemo.MyFirstDeprecatedMethod();
attrDemo.MySecondDeprecatedMethod();
attrDemo.MyThirdDeprecatedMethod();
}
}
>csc BasicAttributeDemo.cs
Microsoft (R) Visual C# .NET Compiler version 7.10.2292.4
for Microsoft (R) .NET Framework version 1.1.4322
Copyright (C) Microsoft Corporation 2001-2002. All rights reserved.
BasicAttributeDemo.cs(29,3): warning CS0612:
'BasicAttributeDemo.MyFirstDeprecatedMethod()' is obsolete
BasicAttributeDemo.cs(30,3): warning CS0612:
'BasicAttributeDemo.MySecondDeprecatedMethod()' is obsolete
BasicAttributeDemo.cs(31,3): warning CS0618:
'BasicAttributeDemo.MyThirdDeprecatedMethod()' is obsolete: 'You
shouldn't use this method anymore.'
class AttributeParamsDemo
{
[DllImport("User32.dll", EntryPoint="MessageBox")]
static extern int MessageDialog(int hWnd, string msg, string caption, int msgType);
[STAThread]
static void Main(string[] args)
{
MessageDialog(0, "MessageDialog Called!", "DllImport Demo", 0);
}
}
Attribute Target Can be Applied To
all everything
assembly entire assembly
class classes
constructor constructors
delegate delegates
enum enumerations
event events
field fields
interface interfaces
method methods
module modules (compiled code that can be part of an assembly)
parameter parameters
property properties
returnvalue return values
struct structures
using System;
[assembly:CLSCompliant(true)]
public class AttributeTargetDemo
{
public void NonClsCompliantMethod(uint nclsParam)//line 6
{
Console.WriteLine("Called NonClsCompliantMethod().");
}
[STAThread]
static void Main(string[] args)
{
uint myUint = 0;
AttributeTargetDemo tgtDemo = new AttributeTargetDemo();
tgtDemo.NonClsCompliantMethod(myUint);
}
}
//it won't compile:
Either change CLSCompliant to false or
change uint type to int type at line 6.
int type is CLSCompliant type.
|