MethodImplAttribute Класс

Определение

Сообщает подробные сведения о реализации метода. Этот класс не наследуется.

public ref class MethodImplAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Constructor | System.AttributeTargets.Method, Inherited=false)]
public sealed class MethodImplAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Constructor | System.AttributeTargets.Method, Inherited=false)]
[System.Serializable]
public sealed class MethodImplAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Constructor | System.AttributeTargets.Method, Inherited=false)]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class MethodImplAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Constructor | System.AttributeTargets.Method, Inherited=false)>]
type MethodImplAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Constructor | System.AttributeTargets.Method, Inherited=false)>]
[<System.Serializable>]
type MethodImplAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Constructor | System.AttributeTargets.Method, Inherited=false)>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MethodImplAttribute = class
    inherit Attribute
Public NotInheritable Class MethodImplAttribute
Inherits Attribute
Наследование
MethodImplAttribute
Атрибуты

Примеры

В следующем примере метод применяется MethodImplAttribute GetCalendarName к методу, чтобы убедиться, что он не встраився во время выполнения компилятором JIT.

using System;
using System.Globalization;
using System.Runtime.CompilerServices;

public class Utility
{
   [MethodImplAttribute(MethodImplOptions.NoInlining)] 
   public static string GetCalendarName(Calendar cal)
   {
      return cal.ToString().Replace("System.Globalization.", "").
                 Replace("Calendar", "");
   }
}
Imports System.Globalization
Imports System.Runtime.CompilerServices

Public Class Utility
   <MethodImplAttribute(MethodImplOptions.NoInlining)>
   Public Shared Function GetCalendarName(cal As Calendar) As String
      Return cal.ToString().Replace("System.Globalization.", "").Replace("Calendar", "")
   End Function
End Class

В следующем примере вызывается MethodInfo.GetMethodImplementationFlags метод, чтобы определить, какие флаги заданы для GetCalendarName метода. В нем также показано, что эти сведения не извлекаются методом MemberInfo.GetCustomAttributes .

using System;
using System.Reflection;

public class Example
{
   public static void Main()
   {
      // Use reflection to get a reference to the GetCalendarName method.
      Assembly assem = Assembly.LoadFrom(@".\Example.dll");
      Type type = assem.GetType("Utility");
      MethodInfo methodInfo = type.GetMethod("GetCalendarName");
      
      // Determine whether the method has any custom attributes.
      Console.Write("Utility.GetCalendarName custom attributes:");
      object[] attribs = methodInfo.GetCustomAttributes(false);
      if (attribs.Length > 0) {
         Console.WriteLine();
         foreach (var attrib in attribs)
            Console.WriteLine("   " + attrib.ToString());   
      }
      else {
         Console.WriteLine("   <None>");
      }

      // Get the method's metadata flags.
      MethodImplAttributes flags = methodInfo.GetMethodImplementationFlags();
      Console.WriteLine("Utility.GetCalendarName flags: {0}", 
                        flags.ToString());      
   }
}
// The example displays the following output:
//     Utility.GetCalendarName custom attributes:   <None>
//     Utility.GetCalendarName flags: NoInlining
Imports System.Reflection

Module Example
   Public Sub Main()
      ' Use reflection to get a reference to the GetCalendarName method.
      Dim assem As Assembly = Assembly.LoadFrom(".\Example.dll")
      Dim type As Type = assem.GetType("Utility")
      Dim methodInfo As MethodInfo = type.GetMethod("GetCalendarName")
      
      ' Determine whether the method has any custom attributes.
      Console.Write("Utility.GetCalendarName custom attributes:")
      Dim attribs() As Object = methodInfo.GetCustomAttributes(False)
      If attribs.Length > 0 Then
         Console.WriteLine()
         For Each attrib As Object In attribs
            Console.WriteLine("   " + attrib.ToString())   
         Next
      Else
         Console.WriteLine("   <None>")
      End If

      ' Get the method's metadata flags.
      Dim flags As MethodImplAttributes = methodInfo.GetMethodImplementationFlags()
      Console.WriteLine("Utility.GetCalendarName flags: {0}", flags.ToString())      
   End Sub
End Module
' The example displays the following output:
'     Utility.GetCalendarName custom attributes:   <None>
'     Utility.GetCalendarName flags: NoInlining

Комментарии

Этот атрибут можно применить к методам или конструкторам.

Этот атрибут позволяет настроить конфигурацию метода или конструктора, к которому он применяется, указав MethodImplOptions значение конструктору класса. Члены перечисления MethodImplOptions соответствуют битовых полям CorMethodImpl в таблице метаданных. Это означает, что сведения об атрибуте невозможно получить во время выполнения путем вызова MemberInfo.GetCustomAttributes метода. Вместо этого он извлекается путем вызова MethodInfo.GetMethodImplementationFlags метода или ConstructorInfo.GetMethodImplementationFlags метода.

Конструкторы

MethodImplAttribute()

Инициализирует новый экземпляр класса MethodImplAttribute.

MethodImplAttribute(Int16)

Инициализирует новый экземпляр класса MethodImplAttribute заданным значением MethodImplOptions.

MethodImplAttribute(MethodImplOptions)

Инициализирует новый экземпляр класса MethodImplAttribute заданным значением MethodImplOptions.

Поля

MethodCodeType

Значение MethodCodeType, указывающее, какого вида реализация предусмотрена для этого метода.

Свойства

TypeId

В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute.

(Унаследовано от Attribute)
Value

Возвращает значение MethodImplOptions, описывающее метод с атрибутами.

Методы

Equals(Object)

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.

(Унаследовано от Attribute)
GetHashCode()

Возвращает хэш-код данного экземпляра.

(Унаследовано от Attribute)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

(Унаследовано от Attribute)
Match(Object)

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к открытым свойствам и методам объекта.

(Унаследовано от Attribute)

Применяется к

См. также раздел