ExpressionPrefixAttribute Classe
Definição
Especifica o atributo de prefixo a ser usado para o construtor de expressões.Specifies the prefix attribute to use for the expression builder. Essa classe não pode ser herdada.This class cannot be inherited.
public ref class ExpressionPrefixAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false)]
public sealed class ExpressionPrefixAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false)>]
type ExpressionPrefixAttribute = class
inherit Attribute
Public NotInheritable Class ExpressionPrefixAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
Os exemplos de código a seguir demonstram como usar a ExpressionPrefixAttribute classe.The following code examples demonstrate how to use the ExpressionPrefixAttribute class. O atributo é aplicado a um construtor de expressões personalizado que implementa a ExpressionBuilder classe abstrata.The attribute is applied to a custom expression builder that implements the ExpressionBuilder abstract class. Essa implementação de ExpressionBuilder retorna uma instrução avaliada que é passada para a expressão.This implementation of ExpressionBuilder returns an evaluated statement that is passed to the expression. Para executar este exemplo, primeiro você deve registrar o construtor de expressões personalizadas no arquivo de Web.config.To run this example, you must first register the custom expression builder in the Web.config file. O primeiro exemplo de código demonstra como registrar o construtor de expressões personalizado no arquivo Web.config.The first code example demonstrates how to register the custom expression builder in the Web.config file.
<configuration>
<system.web>
<compilation>
<expressionBuilders>
<add expressionPrefix="MyCustomExpression"
type="MyCustomExpressionBuilder"/>
</expressionBuilders>
</compilation>
</system.web>
</configuration>
O segundo exemplo de código demonstra como referenciar a expressão em um arquivo. aspx.The second code example demonstrates how to reference the expression in an .aspx file.
<asp:Label ID="Label1" runat="server"
Text="<%$ MyCustomExpression:Hello, world! %>" />
O terceiro exemplo de código demonstra como desenvolver um construtor de expressões personalizado derivando de ExpressionBuilder .The third code example demonstrates how to develop a customized expression builder by deriving from ExpressionBuilder. Para executar este exemplo de código, você deve posicionar a classe na pasta App_Code.To run this code example, you must place the class in the App_Code folder.
using System;
using System.CodeDom;
using System.Web.UI;
using System.ComponentModel;
using System.Web.Compilation;
using System.Web.UI.Design;
// Apply ExpressionEditorAttributes to allow the
// expression to appear in the designer.
[ExpressionPrefix("MyCustomExpression")]
[ExpressionEditor("MyCustomExpressionEditor")]
public class MyExpressionBuilder : ExpressionBuilder
{
// Create a method that will return the result
// set for the expression argument.
public static object GetEvalData(string expression, Type target, string entry)
{
return expression;
}
public override object EvaluateExpression(object target, BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return GetEvalData(entry.Expression, target.GetType(), entry.Name);
}
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
Type type1 = entry.DeclaringType;
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(type1)[entry.PropertyInfo.Name];
CodeExpression[] expressionArray1 = new CodeExpression[3];
expressionArray1[0] = new CodePrimitiveExpression(entry.Expression.Trim());
expressionArray1[1] = new CodeTypeOfExpression(type1);
expressionArray1[2] = new CodePrimitiveExpression(entry.Name);
return new CodeCastExpression(descriptor1.PropertyType, new CodeMethodInvokeExpression(new
CodeTypeReferenceExpression(base.GetType()), "GetEvalData", expressionArray1));
}
public override bool SupportsEvaluate
{
get { return true; }
}
}
Imports System.CodeDom
Imports System.Web.UI
Imports System.ComponentModel
Imports System.Web.Compilation
Imports System.Web.UI.Design
' Apply ExpressionEditorAttributes to allow the
' expression to appear in the designer.
<ExpressionPrefix("MyCustomExpression")> _
<ExpressionEditor("MyCustomExpressionEditor")> _
Public Class MyExpressionBuilder
Inherits ExpressionBuilder
' Create a method that will return the result
' set for the expression argument.
Public Shared Function GetEvalData(ByVal expression As String, _
ByVal target As Type, ByVal entry As String) As Object
Return expression
End Function
Public Overrides Function EvaluateExpression(ByVal target As Object, _
ByVal entry As BoundPropertyEntry, ByVal parsedData As Object, _
ByVal context As ExpressionBuilderContext) As Object
Return GetEvalData(entry.Expression, target.GetType(), entry.Name)
End Function
Public Overrides Function GetCodeExpression(ByVal entry _
As BoundPropertyEntry, ByVal parsedData As Object, ByVal context _
As ExpressionBuilderContext) As CodeExpression
Dim type1 As Type = entry.DeclaringType
Dim descriptor1 As PropertyDescriptor = _
TypeDescriptor.GetProperties(type1)(entry.PropertyInfo.Name)
Dim expressionArray1(2) As CodeExpression
expressionArray1(0) = New CodePrimitiveExpression(entry.Expression.Trim())
expressionArray1(1) = New CodeTypeOfExpression(type1)
expressionArray1(2) = New CodePrimitiveExpression(entry.Name)
Return New CodeCastExpression(descriptor1.PropertyType, _
New CodeMethodInvokeExpression(New CodeTypeReferenceExpression _
(MyBase.GetType()), "GetEvalData", expressionArray1))
End Function
Public Overrides ReadOnly Property SupportsEvaluate() As Boolean
Get
Return True
End Get
End Property
End Class
Comentários
A ExpressionPrefixAttribute classe é usada em tempo de design com expressões que não estão definidas no arquivo de configuração.The ExpressionPrefixAttribute class is used at design time with expressions that are not defined in the configuration file. Use a ExpressionPrefix propriedade para obter o nome do prefixo que está associado ao ExpressionPrefixAttribute objeto.Use the ExpressionPrefix property to get the name of the prefix that is associated with the ExpressionPrefixAttribute object. Um construtor de expressões procura por qualquer instrução com o seguinte formato:An expression builder looks for any statements with the following form:
<%$ [expressionPrefix]:[expressionValue] %>
Em seguida, o construtor de expressões, com base no prefixo da expressão, gera o código para a atribuição de propriedade.Then the expression builder, based on the prefix of the expression, generates code for the property assignment. O expressionPrefix parâmetro refere-se a um construtor de expressões configurado, que é definido no arquivo de configuração ou por meio de um ExpressionPrefixAttribute objeto.The expressionPrefix parameter refers to a configured expression builder, which is defined in the configuration file or through an ExpressionPrefixAttribute object.
Construtores
| ExpressionPrefixAttribute(String) |
Inicializa uma nova instância da classe ExpressionPrefixAttribute.Initializes a new instance of the ExpressionPrefixAttribute class. |
Propriedades
| ExpressionPrefix |
Obtém o valor de prefixo do objeto ExpressionBuilder atual.Gets the prefix value for the current ExpressionBuilder object. |
| 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) |