Attribute.GetCustomAttributes, méthode (MemberInfo, Boolean)
Mise à jour : novembre 2007
Récupère le tableau des attributs personnalisés appliqué à un membre d'un type. Les paramètres spécifient le membre, le type de l'attribut personnalisé à rechercher, et la recherche éventuelle des ancêtres du membre.
Assembly : mscorlib (dans mscorlib.dll)
public static Attribute[] GetCustomAttributes( MemberInfo element, boolean inherit )
public static function GetCustomAttributes( element : MemberInfo, inherit : boolean ) : Attribute[]
Paramètres
- element
- Type : System.Reflection.MemberInfo
Objet dérivé de la classe MemberInfo qui décrit un constructeur, un événement, un champ, une méthode ou un membre de propriété d'une classe.
- inherit
- Type : System.Boolean
Si la valeur est true, spécifie également de rechercher les ancêtres de element pour les attributs personnalisés.
Valeur de retour
Type : System.Attribute[]Tableau Attribute qui contient les attributs personnalisés appliqués à element, ou tableau vide en l'absence de tels attributs personnalisés.
| Exception | Condition |
|---|---|
| ArgumentNullException | element est null. |
| NotSupportedException | element n'est pas un constructeur, une méthode, une propriété, un événement, un type ou un champ. |
| TypeLoadException | Un type d'attribut personnalisé ne peut pas être chargé. |
La valeur de retour contient les attributs personnalisés des ancêtres de element si inherit est true.
Remarque : |
|---|
À partir du .NET Framework version 2.0, cette méthode retourne les attributs de sécurité sur les méthodes, les constructeurs et les types si les attributs sont stockés dans le nouveau format de métadonnées. Les assemblys compilés avec la version 2.0 ou ultérieure utilisent le nouveau format. Les assemblys dynamiques et les assemblys compilés dans des versions précédentes du .NET Framework utilisent l'ancien format XML. Consultez Émission d'attributs de sécurité déclarative. |
L'exemple de code suivant illustre l'utilisation de GetCustomAttributes, avec MemberInfo comme paramètre.
using System; using System.Reflection; using System.Security; using System.Runtime.InteropServices; namespace CustAttrs4CS { // Define an enumeration of Win32 unmanaged types public enum UnmanagedType { User, GDI, Kernel, Shell, Networking, Multimedia } // Define the Unmanaged attribute. public class UnmanagedAttribute : Attribute { // Storage for the UnmanagedType value. protected UnmanagedType thisType; // Set the unmanaged type in the constructor. public UnmanagedAttribute(UnmanagedType type) { thisType = type; } // Define a property to get and set the UnmanagedType value. public UnmanagedType Win32Type { get { return thisType; } set { thisType = Win32Type; } } } // Create a class for an imported Win32 unmanaged function. public class Win32 { [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int MessageBox(int hWnd, String text, String caption, uint type); } public class AClass { // Add some attributes to Win32CallMethod. [Obsolete("This method is obsolete. Use managed MsgBox instead.")] [Unmanaged(UnmanagedType.User)] public void Win32CallMethod() { Win32.MessageBox(0, "This is an unmanaged call.", "Caution!", 0); } } class DemoClass { static void Main(string[] args) { // Get the AClass type to access its metadata. Type clsType = typeof(AClass); // Get the type information for Win32CallMethod. MethodInfo mInfo = clsType.GetMethod("Win32CallMethod"); if (mInfo != null) { // Iterate through all the attributes of the method. foreach(Attribute attr in Attribute.GetCustomAttributes(mInfo)) { // Check for the Obsolete attribute. if (attr.GetType() == typeof(ObsoleteAttribute)) { Console.WriteLine("Method {0} is obsolete. " + "The message is:", mInfo.Name); Console.WriteLine(" \"{0}\"", ((ObsoleteAttribute)attr).Message); } // Check for the Unmanaged attribute. else if (attr.GetType() == typeof(UnmanagedAttribute)) { Console.WriteLine( "This method calls unmanaged code."); Console.WriteLine( String.Format("The Unmanaged attribute type is {0}.", ((UnmanagedAttribute)attr).Win32Type)); AClass myCls = new AClass(); myCls.Win32CallMethod(); } } } } } } /* This code example produces the following results. First, the compilation yields the warning, "...This method is obsolete. Use managed MsgBox instead." Second, execution yields a message box with a title of "Caution!" and message text of "This is an unmanaged call." Third, the following text is displayed in the console window: Method Win32CallMethod is obsolete. The message is: "This method is obsolete. Use managed MsgBox instead." This method calls unmanaged code. The Unmanaged attribute type is User. */
package CustAttrs4JSL;
import System.*;
import System.Reflection.*;
import System.Security.*;
import System.Runtime.InteropServices.*;
// Define an enumeration of Win32 unmanaged types
public enum UnmanagedType
{
User,
GDI,
Kernel,
Shell,
Networking,
Multimedia
}
// Define the Unmanaged attribute.
public class UnmanagedAttribute extends Attribute
{
// Storage for the UnmanagedType value.
private UnmanagedType thisType;
// Set the unmanaged type in the constructor.
public UnmanagedAttribute(UnmanagedType type)
{
thisType = type;
}
// Define a property to get and set the UnmanagedType value.
public UnmanagedType get_thisType()
{
return thisType;
}
public void set_thisType(UnmanagedType Win32Type)
{
thisType = Win32Type;
}
}
// Create a class for Win32 imported unmanaged functions.
public class Win32
{
/** @attribute DllImport("user32.dll", CharSet = CharSet.Unicode)
*/
public static native int MessageBox(int hWnd, String text,
String caption, UInt32 type);
} //Win32
public class AClass
{
// Add some attributes to the Win32CallMethod.
/** @attribute Obsolete("This method is obsolete."
+ "Use managed MsgBox instead.")
*/
public void Win32CallMethod()
{
Win32.MessageBox(0, "This is an unmanaged call.", "Be Careful!",
(UInt32)0);
} //Win32CallMethod
} //AClass
class DemoClass
{
public static void main(String[] args)
{
// Get the Class type to access its metadata.
Type clsType = AClass.class.ToType();
// Get the type information for the Win32CallMethod.
MethodInfo mInfo = clsType.GetMethod("Win32CallMethod");
if (mInfo != null) {
// Iterate through all the attributes for the method.
for (int iCtr = 0; iCtr < Attribute.GetCustomAttributes(mInfo).
get_Length(); iCtr++) {
Attribute attr = (Attribute)Attribute.
GetCustomAttributes(mInfo).get_Item(iCtr);
// Check for the Obsolete attribute.
if (attr.GetType().Equals(ObsoleteAttribute.class.ToType())) {
Console.WriteLine("Method {0} is obsolete. " +
"The message is:", mInfo.get_Name());
Console.WriteLine(((ObsoleteAttribute)attr).get_Message());
}
// Check for the SuppressUnmanagedCodeSecurity attribute.
else {
if (attr.GetType().Equals(
SuppressUnmanagedCodeSecurityAttribute.class.
ToType())) {
Console.WriteLine("This method calls unmanaged code "
+ "with no security check.");
Console.WriteLine("Please do not use unless absolutely"
+" necessary.");
AClass myCls = new AClass();
myCls.Win32CallMethod();
}
}
}
}
} //main
} //DemoClass
/*
Output:
Method Win32CallMethod is obsolete. The message is:
This method is obsolete. Use managed MsgBox instead.
This method calls unmanaged code with no security check.
Please do not use unless absolutely necessary.
*/
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professionnel Édition x64, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile pour Smartphone, Windows Mobile pour Pocket PC, Xbox 360
Le .NET Framework et le .NET Compact Framework ne prennent pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.
Remarque :