使用属性
属性表示或存储有关类和方法行为的元数据。 属性可通过在需要应用的类/函数声明之前键入以方括号引用的属性名称来附加。
示例
例如,SysObsoleteAttribute(message,setError) 属性可用于不应再使用的方法或类。 在生成过程中,将通过在输出窗口中显示详细消息的方式通知用户。 第一个参数是消息,第二个参数指示是否要设置错误 (true) 或警告 (false)。 您可以指示编译器拒绝或显示警告。
如果 API 不再正常运行,则在 SysObsoleteAttribute 属性中设置 isError = true,以便编译器将该 API 的任何使用报告为编译器错误
[SysObsoleteAttribute("The Automobile class might have faster performance.", false)]
internal class Bicycle
{
// Members of the Bicycle class go here.
}
属性类
使用属性类也可以创建属性。 要创建属性类,请通过在类声明结束位置添加 extend SysAttribute 来扩展 SysAttribute 类。
然后,您可以使用从属性类创建的属性来修饰类。 您可以从构造函数中指定属性参数。 在以下代码中,将创建 PracticeAttribute 属性类,然后,RegularClass 类使用 PracticeAttribute 作为属性。
示例
以下示例显示了可创建的普通属性类的声明和设计。
public class PracticeAttribute extends SysAttribute
{
// Fields in the classDeclaration.
StartEnd startEndEnum;
str reason;
}
// Constructor.
public void new(StartEnd _startEndEnum, str _reason)
{
startEndEnum = _startEndEnum;
reason = _reason;
}
[PracticeAttribute(StartEnd::End, "Use the RegularClass class at the end.")]
public class RegularClass
{
[PracticeAttribute(Startend::Start, "Use the rehearse method at the start.")]
public int rehearse()
{
// Logic goes here.
int rehearse;
return rehearse;
}
// More fields and methods belong here.
}
属性具有多种用途,包括:
- 使用 Web 服务中的
WebMethod属性指示是否应可通过简单对象访问协议 (SOAP) 调用该方法来交换信息。 - 用于
DLLImportAttribute调用非托管代码。 - 描述程序集的标题、版本、描述或商标。
- 描述如何在类、成员和可扩展标记语言 (XML) 节点之间映射以进行序列化。
- 描述方法的安全性要求。
- 指定用于强制实施安全性的特征。
- 获取有关方法调用方的信息。
资源
若要了解详细信息,请参阅类和方法。