IteratorStateMachineAttribute Classe
Definição
Indica se um método no Visual Basic é marcado com o modificador Iterator
.Indicates whether a method in Visual Basic is marked with the Iterator
modifier.
public ref class IteratorStateMachineAttribute sealed : System::Runtime::CompilerServices::StateMachineAttribute
public sealed class IteratorStateMachineAttribute : System.Runtime.CompilerServices.StateMachineAttribute
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
public sealed class IteratorStateMachineAttribute : System.Runtime.CompilerServices.StateMachineAttribute
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
[System.Serializable]
public sealed class IteratorStateMachineAttribute : System.Runtime.CompilerServices.StateMachineAttribute
type IteratorStateMachineAttribute = class
inherit StateMachineAttribute
[<System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)>]
type IteratorStateMachineAttribute = class
inherit StateMachineAttribute
[<System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)>]
[<System.Serializable>]
type IteratorStateMachineAttribute = class
inherit StateMachineAttribute
Public NotInheritable Class IteratorStateMachineAttribute
Inherits StateMachineAttribute
- Herança
- Atributos
Exemplos
O exemplo a seguir mostra como determinar se um método é um método iterador.The following example shows how to determine whether a method is an iterator method. No exemplo, IsIteratorMethod
o executa as seguintes etapas:In the example, IsIteratorMethod
performs the following steps:
Obtém um MethodInfo objeto para o nome do método usando Type.GetMethod .Obtains a MethodInfo object for the method name by using Type.GetMethod.
Obtém um Type objeto para o atributo usando o Operador GetType.Obtains a Type object for the attribute by using GetType Operator.
Obtém um objeto de atributo para o método e o tipo de atributo usando
MethodInfo.GetCustomAttribute
.Obtains an attribute object for the method and attribute type by usingMethodInfo.GetCustomAttribute
. SeGetCustomAttribute
retornaNothing
(Visual Basic), o método não contém o atributo.IfGetCustomAttribute
returnsNothing
(Visual Basic), the method doesn't contain the attribute.
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Module Module1
' This class is used by the code below to discover method attributes.
Public Class TheClass
Public Async Function AsyncMethod() As Task(Of Integer)
Await Task.Delay(5)
Return 1
End Function
Public Iterator Function IteratorMethod() As IEnumerable(Of Integer)
Yield 1
Yield 2
End Function
Public Function RegularMethod() As Integer
Return 0
End Function
End Class
Private Function IsAsyncMethod(classType As Type, methodName As String)
' Obtain the method with the specified name.
Dim method As MethodInfo = classType.GetMethod(methodName)
Dim attType As Type = GetType(AsyncStateMachineAttribute)
Dim attrib = CType(method.GetCustomAttribute(attType), AsyncStateMachineAttribute)
' The above variable contains the StateMachineType property.
Return (attrib IsNot Nothing)
End Function
Private Function IsIteratorMethod(classType As Type, methodName As String)
' Obtain the method with the specified name.
Dim method As MethodInfo = classType.GetMethod(methodName)
Dim attType As Type = GetType(IteratorStateMachineAttribute)
' Obtain the custom attribute for the method.
' The value returned contains the StateMachineType property.
' Nothing is returned if the attribute isn't present for the method.
Dim attrib = CType(method.GetCustomAttribute(attType), IteratorStateMachineAttribute)
Return (attrib IsNot Nothing)
End Function
Private Sub ShowResult(classType As Type, methodName As String)
Console.Write((methodName & ": ").PadRight(16))
If IsAsyncMethod(classType, methodName) Then
Console.WriteLine("Async method")
ElseIf IsIteratorMethod(classType, methodName) Then
Console.WriteLine("Iterator method")
Else
Console.WriteLine("Regular method")
End If
' Note: The IteratorStateMachineAttribute applies to Visual Basic methods
' but not C# methods.
End Sub
Sub Main()
ShowResult(GetType(TheClass), "AsyncMethod")
ShowResult(GetType(TheClass), "IteratorMethod")
ShowResult(GetType(TheClass), "RegularMethod")
Console.ReadKey()
End Sub
' AsyncMethod: Async method
' IteratorMethod: Iterator method
' RegularMethod: Regular method
End Module
Comentários
Você não deve aplicar o IteratorStateMachine
atributo a métodos em seu código.You shouldn't apply the IteratorStateMachine
attribute to methods in your code. Para métodos em Visual Basic que têm o modificador de iterador , o compilador aplicará o IteratorStateMachine
atributo no Il que ele emitir.For methods in Visual Basic that have the Iterator modifier, the compiler will apply the IteratorStateMachine
attribute in the IL that it emits.
Quando um método ( MethodName ) em Visual Basic tem o Iterator
modificador, o compilador emite Il que inclui uma estrutura de máquina de estado.When a method ( MethodName ) in Visual Basic has the Iterator
modifier, the compiler emits IL that includes a state machine structure. Essa estrutura contém o código no método.That structure contains the code in the method. Esse IL também contém um método stub ( MethodName ) que chama para o computador de estado.That IL also contains a stub method ( MethodName ) that calls into the state machine. O compilador adiciona o IteratorStateMachine
atributo ao método de stub para que as ferramentas possam identificar o computador de estado correspondente.The compiler adds the IteratorStateMachine
attribute to the stub method so that tools can identify the corresponding state machine. Os detalhes do IL emitido podem ser alterados em versões futuras dos compiladores.Details of the emitted IL might change in future releases of the compilers.
Um método iterador executa uma iteração personalizada em uma coleção usando a Yield
instrução (Visual Basic) para retornar cada elemento um de cada vez.An iterator method performs a custom iteration over a collection by using the Yield
(Visual Basic) statement to return each element one at a time. Para obter mais informações, consulte Iteradores.For more information, see Iterators.
Observação
Você não pode usar IteratorStateMachineAttribute
o para testar se um método é um método iterador em C#.You can't use IteratorStateMachineAttribute
to test whether a method is an iterator method in C#.
Construtores
IteratorStateMachineAttribute(Type) |
Inicializa uma nova instância da classe IteratorStateMachineAttribute.Initializes a new instance of the IteratorStateMachineAttribute class. |
Propriedades
StateMachineType |
Retorna o objeto de tipo para o tipo de computador de estado subjacente gerado pelo compilador para implementar o método de computador de estado.Returns the type object for the underlying state machine type that was generated by the compiler to implement the state machine method. (Herdado de StateMachineAttribute) |
TypeId |
Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute. (Herdado de Attribute) |
Métodos
Equals(Object) |
Retorna um valor que indica se essa instância é igual a um objeto especificado.Returns a value that indicates whether this instance is equal to a specified object. (Herdado de Attribute) |
GetHashCode() |
Retorna o código hash para a instância.Returns the hash code for this instance. (Herdado de Attribute) |
GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
IsDefaultAttribute() |
Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Herdado de Attribute) |
Match(Object) |
Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Herdado de Attribute) |
MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
Implantações explícitas de interface
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers. (Herdado de Attribute) |
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.Retrieves the type information for an object, which can be used to get the type information for an interface. (Herdado de Attribute) |
_Attribute.GetTypeInfoCount(UInt32) |
Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Herdado de Attribute) |
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object. (Herdado de Attribute) |