Compartir a través de


<Elemento Method> (.NET Native)

Aplica la directiva de reflexión en tiempo de ejecución a un constructor o método.

Sintaxis

<Method Name="method_name"
        Signature="method_signature"
        Browse="policy_type"
        Dynamic="policy_type" />

Atributos y elementos

En las siguientes secciones se describen los atributos, los elementos secundarios y los elementos primarios.

Atributos

Attribute Tipo de atributo Descripción
Name General Atributo necesario. Especifica el nombre del método.
Signature General Atributo opcional. Especifica la signatura del método. Si hay varios parámetros, se separan mediante comas. Por ejemplo, el elemento <Method> siguiente define la política del método ToString(String, IFormatProvider).

<Type Name="System.DateTime"> <Method Name="ToString" Signature="System.String,System.IFormatProvider" Dynamic="Required" /> </Type>

Si el atributo no está presente, la directiva de tiempo de ejecución se aplica a todas las sobrecargas del método.
Browse Reflexión Atributo opcional. Controla la consulta para obtener información acerca de un método o la enumeración de un método, pero no permite la invocación dinámica en tiempo de ejecución.
Dynamic Reflexión Atributo opcional. Controla el acceso en tiempo de ejecución a un constructor o un método para habilitar la programación dinámica. Esta directiva garantiza que un miembro se puede invocar dinámicamente en tiempo de ejecución.

Name (atributo)

Valor Descripción
method_name El nombre del método. El tipo del método se define mediante el elemento primario <Type> o <TypeInstantiation.>

Signature (atributo)

Valor Descripción
method_signature Los tipos de parámetros que constituyen la signatura del método. Si hay varios parámetros, se separan por comas; por ejemplo, "System.String,System.Int32,System.Int32)". Los nombres de tipo de parámetro deben ser completos.

Resto de atributos

Valor Descripción
policy_setting Configuración que se va a aplicar a este tipo de directiva. Los valores posibles son Auto, Excluded, Included y Required. Para obtener más información, vea Runtime Directive Policy Settings (Configuración de directiva de la directiva en tiempo de ejecución).

Elementos secundarios

Elemento Descripción
<Parámetro> Aplica la directiva al tipo del argumento que se pasa a un método.
<GenericParameter> Aplica la directiva al tipo de parámetro de un método o tipo genérico.
<ImpliesType> Aplica la directiva a un tipo, si esa directiva se ha aplicado al método representado por el elemento <Method> contenedor.
<TypeParameter> Aplica la directiva al tipo representado por un argumento Type que se pasa a un método.

Elementos primarios

Elemento Descripción
<Tipo> Aplica la directiva de reflexión a un tipo y a todos sus miembros.
<TypeInstantiation> Aplica la directiva de reflexión a un tipo genérico construido y a todos sus miembros.

Comentarios

Un elemento <Method> de un método genérico aplica su directiva a todas las instancias que no tienen su propia directiva.

Puede utilizar el atributo Signature para especificar la directiva de sobrecarga de un método determinado. Por otra parte, si el atributo Signature no está presente, la directiva de tiempo de ejecución se aplica a todas las sobrecargas del método.

No se puede definir la directiva de reflexión en tiempo de ejecución para un constructor mediante el uso del elemento <Method>. En su lugar, use el Activate atributo del< elemento Assembly>, <Namespace>, <Type> o< TypeInstantiation.>

Ejemplo

El método Stringify del siguiente ejemplo es un método de formato de uso general que utiliza la reflexión para convertir un objeto en su representación de cadena. Además de llamar al método ToString predeterminado del objeto, el método puede generar una cadena de resultado con formato; para ello, se pasa el método ToString de un objeto a una cadena de formato, a una implementación de IFormatProvider o a ambos. También puede llamar a una de las sobrecargas Convert.ToString que convierte un número en su representación binaria, octal o hexadecimal.

public class Stringify
{
   public static string ConvertToString(Object[] obj)
   {
      if (obj == null)
         throw new NullReferenceException("The obj parameter cannot be null.");

      if (obj.Length == 0) return String.Empty;

      if (obj[0].GetType() == typeof(String))
         return obj[0] as string;

      if (obj.Length == 1) return obj[0].ToString();

      if (obj.Length > 3)
         throw new ArgumentOutOfRangeException("The array can have from zero to three elements.");

      string retval = "";

      // Parameters indicate either a format specifier, numeric base, or format provider,
      // or a format specifier with an IFormatProvider.

      // A string as the first parameter indicates a format specifier.
      if (obj[1].GetType() == typeof(String)) {
         Type t = obj[0].GetType();
         if (obj.Length == 2)
         {
            MethodInfo m = t.GetRuntimeMethod("ToString", new Type[] { typeof(String) });
            retval = m.Invoke(obj[0], new object[] { obj[1] }).ToString();
         }
         else
         {
             MethodInfo m = t.GetRuntimeMethod("ToString", new Type[] { typeof(String), obj[2].GetType() });
             retval = m.Invoke(obj[0], new object[] { obj[1], obj[2] }).ToString();
         }
      }
      else if (obj[1] is IFormatProvider)
      {
          Type t = obj[0].GetType();
          MethodInfo m = t.GetRuntimeMethod("ToString", new Type[] { obj[1].GetType() } );
          retval = m.Invoke(obj[0], new object[] { obj[1] }).ToString();
      }
      // The second parameter is a base, so call Convert.ToString(number, int).
      else {
          Type t = typeof(Convert);
          MethodInfo m = t.GetRuntimeMethod("ToString", new Type[] { obj[0].GetType(), obj[1].GetType() } );
          retval = m.Invoke(null, obj).ToString();
      }
      return retval;
   }
}

El método Stringify puede llamarse mediante código como el siguiente:

public class Stringify
{
   public static string ConvertToString(Object[] obj)
   {
      if (obj == null)
         throw new NullReferenceException("The obj parameter cannot be null.");

      if (obj.Length == 0) return String.Empty;

      if (obj[0].GetType() == typeof(String))
         return obj[0] as string;

      if (obj.Length == 1) return obj[0].ToString();

      if (obj.Length > 3)
         throw new ArgumentOutOfRangeException("The array can have from zero to three elements.");

      string retval = "";

      // Parameters indicate either a format specifier, numeric base, or format provider,
      // or a format specifier with an IFormatProvider.

      // A string as the first parameter indicates a format specifier.
      if (obj[1].GetType() == typeof(String)) {
         Type t = obj[0].GetType();
         if (obj.Length == 2)
         {
            MethodInfo m = t.GetRuntimeMethod("ToString", new Type[] { typeof(String) });
            retval = m.Invoke(obj[0], new object[] { obj[1] }).ToString();
         }
         else
         {
             MethodInfo m = t.GetRuntimeMethod("ToString", new Type[] { typeof(String), obj[2].GetType() });
             retval = m.Invoke(obj[0], new object[] { obj[1], obj[2] }).ToString();
         }
      }
      else if (obj[1] is IFormatProvider)
      {
          Type t = obj[0].GetType();
          MethodInfo m = t.GetRuntimeMethod("ToString", new Type[] { obj[1].GetType() } );
          retval = m.Invoke(obj[0], new object[] { obj[1] }).ToString();
      }
      // The second parameter is a base, so call Convert.ToString(number, int).
      else {
          Type t = typeof(Convert);
          MethodInfo m = t.GetRuntimeMethod("ToString", new Type[] { obj[0].GetType(), obj[1].GetType() } );
          retval = m.Invoke(null, obj).ToString();
      }
      return retval;
   }
}

Sin embargo, cuando se compila con .NET Native, el ejemplo puede producir una serie de excepciones en tiempo de ejecución, incluidas NullReferenceException las excepciones MissingRuntimeArtifactException , esto se produce porque el Stringify método está pensado principalmente para admitir el formato dinámico de los tipos primitivos en la biblioteca de clases de .NET Framework. No obstante, sus metadatos no están disponibles en el archivo de directivas predeterminado. Incluso cuando sus metadatos están disponibles, el ejemplo genera excepciones MissingRuntimeArtifactException porque las implementaciones ToString adecuadas no se han incluido en el código nativo.

Todas estas excepciones se pueden eliminar mediante el <elemento Type> para definir los tipos cuyos metadatos deben estar presentes y agregando <Method> elementos para asegurarse de que la implementación de sobrecargas de método a las que se puede llamar dinámicamente también está presente. El siguiente es el archivo default.rd.xml que elimina estas excepciones y permite que el ejemplo se ejecute sin errores.

<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
  <Application>
     <Assembly Name="*Application*" Dynamic="Required All" />

     <Type Name = "System.Convert" Browse="Required Public" Dynamic="Required Public" >
        <Method Name="ToString"    Dynamic ="Required" />
     </Type>
     <Type Name="System.Double" Browse="Required Public">
        <Method Name="ToString" Dynamic="Required" />
     </Type>
     <Type Name ="System.Int32" Browse="Required Public" >
        <Method Name="ToString" Dynamic="Required" />
     </Type>
     <Type Name ="System.Int64" Browse="Required Public" >
        <Method Name="ToString" Dynamic="Required" />
     </Type>
     <Namespace Name="System" >
        <Type Name="Byte" Browse="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="DateTime" Browse="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="Decimal" Browse="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="Guid" Browse ="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="Int16" Browse="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="SByte" Browse="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="Single" Browse="Required Public" >
          <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="TimeSpan" Browse="Required Public" >
          <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="UInt16" Browse="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="UInt32" Browse="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
        <Type Name="UInt64" Browse="Required Public" >
           <Method Name="ToString" Dynamic="Required" />
        </Type>
     </Namespace>
  </Application>
</Directives>

Consulte también