8.14 Attributes

本文介绍了C#中属性(Attributes)的相关内容。C#虽是命令式语言,但有声明式元素,可定义和使用属性添加额外声明信息。文中以HelpAttribute为例,展示了属性类的定义、参数设置及使用,还说明了如何在运行时通过反射获取属性信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

8.14 Attributes
C# is an imperative language, but like all imperative languages it does have
some declarative elements. For
example, the accessibility of a method in a class is specified by declaring
it public, protected,
internal, protected internal, or private. C# generalizes this capability,
so that programmers can
invent new kinds of declarative information, attach this declarative
information to various program entities,
and retrieve this declarative information at run-time. Programs specify
this additional declarative
information by defining and using attributes (§24).
For instance, a framework might define a HelpAttribute attribute that can
be placed on program elements
such as classes and methods, enabling developers to provide a mapping from
program elements to
documentation for them. The example
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute: Attribute
{
public HelpAttribute(string url) {
this.url = url;
}
public string Topic = null;
private string url;
Chapter 8 Language Overview
49
public string Url {
get { return url; }
}
}
defines an attribute class named HelpAttribute, or Help for short, that has
one positional parameter
(string url) and one named parameter (string Topic). Positional parameters
are defined by the
formal parameters for public instance constructors of the attribute class,
and named parameters are defined
by public non-static read-write fields and properties of the attribute
class.
The example
[Help(" http://www.mycompany.com/./Class1.htm )]
public class Class1
{
[Help(" http://www.mycompany.com/./Class1.htm , Topic = "F")]
public void F() {}
}
shows several uses of the attribute Help.
Attribute information for a given program element can be retrieved at
run-time by using reflection support.
The example
using System;
class Test
{
static void Main() {
Type type = typeof(Class1);
object[] arr = type.GetCustomAttributes(typeof(HelpAttribute),
true);
if (arr.Length == 0)
Console.WriteLine("Class1 has no Help attribute.");
else {
HelpAttribute ha = (HelpAttribute) arr[0];
Console.WriteLine("Url = {0}, Topic = {1}", ha.Url, ha.Topic);
}
}
}
checks to see if Class1 has a Help attribute, and writes out the associated
Topic and Url values if the
attribute is present.
End of informative text.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值