ObsoleteAttribute Clase
Definición
Marca los elementos del programa que ya no se utilizan.Marks the program elements that are no longer in use. Esta clase no puede heredarse.This class cannot be inherited.
public ref class ObsoleteAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, Inherited=false)]
public sealed class ObsoleteAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, Inherited=false)]
[System.Serializable]
public sealed class ObsoleteAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, Inherited=false)]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ObsoleteAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, Inherited=false)>]
type ObsoleteAttribute = class
inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, Inherited=false)>]
[<System.Serializable>]
type ObsoleteAttribute = class
inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property | System.AttributeTargets.Struct, Inherited=false)>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ObsoleteAttribute = class
inherit Attribute
Public NotInheritable Class ObsoleteAttribute
Inherits Attribute
- Herencia
- Atributos
Ejemplos
En el ejemplo siguiente se define una clase que contiene una propiedad y un método marcados con el ObsoleteAttribute atributo.The following example defines a class that contains a property and a method that are marked with the ObsoleteAttribute attribute. El acceso al valor de la OldProperty
propiedad en el código genera una advertencia del compilador, pero la llamada al CallOldMethod
método genera un error del compilador.Accessing the value of the OldProperty
property in code generates a compiler warning, but calling the CallOldMethod
method generates a compiler error. En el ejemplo también se muestra el resultado que se obtiene al intentar compilar el código fuente.The example also shows the output that results when you attempt to compile the source code.
using System;
using System.Reflection;
public class Example
{
// Mark OldProperty As Obsolete.
[ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", false)]
public static string OldProperty
{ get { return "The old property value."; } }
public static string NewProperty
{ get { return "The new property value."; } }
// Mark CallOldMethod As Obsolete.
[ObsoleteAttribute("This method is obsolete. Call CallNewMethod instead.", true)]
public static string CallOldMethod()
{
return "You have called CallOldMethod.";
}
public static string CallNewMethod()
{
return "You have called CallNewMethod.";
}
public static void Main()
{
Console.WriteLine(OldProperty);
Console.WriteLine();
Console.WriteLine(CallOldMethod());
}
}
// The attempt to compile this example produces output like the following output:
// Example.cs(31,25): error CS0619: 'Example.CallOldMethod()' is obsolete:
// 'This method is obsolete. Call CallNewMethod instead.'
// Example.cs(29,25): warning CS0618: 'Example.OldProperty' is obsolete:
// 'This property is obsolete. Use NewProperty instead.'
Imports System.Reflection
Public Module Example
' Mark OldProperty As Obsolete.
<ObsoleteAttribute("This property is obsolete. Use NewProperty instead.", False)>
Public ReadOnly Property OldProperty As String
Get
Return "The old property value."
End Get
End Property
Public ReadOnly Property NewProperty As String
Get
Return "The new property value."
End Get
End Property
' Mark OldMethod As Obsolete.
<ObsoleteAttribute("This method is obsolete. Call CallNewMethod instead.", True)>
Public Function CallOldMethod() As String
Return "You have called CallOldMethod."
End Function
Public Function CallNewMethod() As String
Return "You have called NewMethod."
End Function
Public Sub Main()
Console.WriteLine(OldProperty)
Console.WriteLine()
Console.WriteLine(CallOldMethod())
End Sub
End Module
' The attempt to compile this example produces output like the following:
' Example.vb(30) : warning BC40000: 'Public ReadOnly Property OldProperty As String' is obsolete:
' 'This property is obsolete. Use NewProperty instead.'.
'
' Console.WriteLine(OldProperty)
' ~~~~~~~~~~~
' Example.vb(32) : error BC30668: 'Public Function CallOldMethod() As String' is obsolete:
' 'This method is obsolete. Call CallNewMethod instead.'.
'
' Console.WriteLine(CallOldMethod())
' ~~~~~~~~~~~~~
Comentarios
ObsoleteAttribute es aplicable a todos los elementos de programa, excepto los ensamblados, los módulos, los parámetros y los valores devueltos.ObsoleteAttribute is applicable to all program elements except assemblies, modules, parameters, and return values. Al marcar un elemento como obsoleto, se informa a los usuarios de que el elemento puede quitarse en una versión futura del producto.Marking an element as obsolete informs users that the element may be removed in a future version of the product.
El compilador emite la cadena asignada a la Message propiedad cuando el destino del atributo se utiliza en el código.The string assigned to the Message property is emitted by the compiler when the attribute target is used in code. Idealmente, la cadena debe proporcionar alguna alternativa o alternativa mediante programación.Ideally, the string should provide some workaround or programmatic alternative.
Utilice la IsError propiedad para indicar al compilador si el uso del ObsoleteAttribute atributo debe hacer que emita un error ( IsError es true
) o una advertencia ( IsError es false
).Use the IsError property to indicate to the compiler whether using the ObsoleteAttribute attribute should cause it to emit an error (IsError is true
) or a warning (IsError is false
).
Para obtener más información sobre el uso de atributos, vea atributos.For more information about using attributes, see Attributes.
Aplicaciones de la tienda Windows 8. xWindows 8.x Store apps
Cuando se crea una biblioteca de metadatos de Windows (archivo. winmd), ObsoleteAttribute se exporta como el atributo ObsoleteAttribute y el atributo Windows. Foundation. Metadata. DeprecatedAttribute si solo ObsoleteAttribute está presente en el código fuente.When you create a Windows Metadata library (.winmd file), the ObsoleteAttribute is exported as both the ObsoleteAttribute attribute and the Windows.Foundation.Metadata.DeprecatedAttribute attribute if only the ObsoleteAttribute is present in source code. El ObsoleteAttribute se transforma en de la DeprecatedAttribute
manera siguiente:The ObsoleteAttribute is transformed to the DeprecatedAttribute
as follows:
Si los
message
error
argumentos y están presentes,message
se asigna alDeprecatedAttribute
message
argumento.If themessage
anderror
arguments are both present,message
is assigned to theDeprecatedAttribute
message
argument. Un valor de error detrue
se asigna a DeprecationType. Removey unerror
valor defalse
se asigna a DeprecationType. deprecated.An error value oftrue
maps to DeprecationType.Remove, and anerror
value offalse
maps to DeprecationType.Deprecate.Si el
message
argumento no se proporciona en ObsoleteAttribute , su valor predeterminado enDeprecatedAttribute
es "element_name está en desuso", donde element_name es el nombre del elemento del programa de destino al que se aplica el atributo.If themessage
argument is not supplied in the ObsoleteAttribute, its default value in theDeprecatedAttribute
is "element_name is deprecated", where element_name is the name of the target program element to which the attribute is applied.Si el
error
argumento no está presente en ObsoleteAttribute , su valor predeterminado enDeprecatedAttribute
es DeprecationType.Deprecate .If theerror
argument is not present in the ObsoleteAttribute, its default value in theDeprecatedAttribute
is DeprecationType.Deprecate.
Importante
No se recomienda aplicar directamente el atributo Windows. Foundation. Metadata. DeprecatedAttribute al código administrado, porque esta exportación se produce automáticamente.Directly applying the Windows.Foundation.Metadata.DeprecatedAttribute attribute to managed code is not recommended, because this export occurs automatically.
Constructores
ObsoleteAttribute() |
Inicializa una nueva instancia de la clase ObsoleteAttribute con propiedades predeterminadas.Initializes a new instance of the ObsoleteAttribute class with default properties. |
ObsoleteAttribute(String) |
Inicializa una nueva instancia de la clase ObsoleteAttribute con el mensaje de solución especificado.Initializes a new instance of the ObsoleteAttribute class with a specified workaround message. |
ObsoleteAttribute(String, Boolean) |
Inicializa una nueva instancia de la clase ObsoleteAttribute con un mensaje de solución y un valor Boolean que indica si el uso del elemento obsoleto se considera un error.Initializes a new instance of the ObsoleteAttribute class with a workaround message and a Boolean value indicating whether the obsolete element usage is considered an error. |
Propiedades
DiagnosticId |
Obtiene o establece el identificador que utilizará el compilador al notificar un uso de la API.Gets or sets the ID that the compiler will use when reporting a use of the API. |
IsError |
Obtiene un valor que indica si el compilador tratará el uso del elemento de programa obsoleto como un error.Gets a value that indicates whether the compiler will treat usage of the obsolete program element as an error. |
Message |
Obtiene el mensaje de la solución.Gets the workaround message. |
TypeId |
Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute. (Heredado de Attribute) |
UrlFormat |
Obtiene o establece la dirección URL de la documentación correspondiente.Gets or sets the URL for corresponding documentation. La API acepta una cadena de formato en lugar de una dirección URL real y crea una dirección URL genérica que incluye el identificador de diagnóstico.The API accepts a format string instead of an actual URL, creating a generic URL that includes the diagnostic ID. |
Métodos
Equals(Object) |
Devuelve un valor que indica si esta instancia es igual que un objeto especificado.Returns a value that indicates whether this instance is equal to a specified object. (Heredado de Attribute) |
GetHashCode() |
Devuelve el código hash de esta instancia.Returns the hash code for this instance. (Heredado de Attribute) |
GetType() |
Obtiene el Type de la instancia actual.Gets the Type of the current instance. (Heredado de Object) |
IsDefaultAttribute() |
Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Heredado de Attribute) |
Match(Object) |
Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Heredado de Attribute) |
MemberwiseClone() |
Crea una copia superficial del Object actual.Creates a shallow copy of the current Object. (Heredado de Object) |
ToString() |
Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object. (Heredado de Object) |
Implementaciones de interfaz explícitas
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.Maps a set of names to a corresponding set of dispatch identifiers. (Heredado de Attribute) |
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.Retrieves the type information for an object, which can be used to get the type information for an interface. (Heredado de Attribute) |
_Attribute.GetTypeInfoCount(UInt32) |
Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Heredado de Attribute) |
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Proporciona acceso a las propiedades y los métodos expuestos por un objeto.Provides access to properties and methods exposed by an object. (Heredado de Attribute) |