Attributes (C#)
编程语言的易用性,很多时候得益于元数据,越多则可以从中得到的提示越多,从而编写代码的时候感觉更顺滑。
C#中的属性将元数据(即声明性信息)与代码结合起来。可以运行时用于反射https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection。
属性有下列性质(properties):
- 属性添加元数据到程序中。元数据主要保存跟类型相关的信息。.NET的配装件中就是所包含类型的元数据。
- 可以给程序中不同范围、跨度、大小的实体添加元数据。
- 属性像方法和特质(properties)一样,可以接受参量。
- 程序可以通过反射机制探知自己的元数据。
Using attributes
任意的声明上都可以有元数据,只是内容上会有所不同。示例如下:
[Serializable]
public class SampleClass
{
// Objects of this type can be serialized.
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static void SampleMethod();
示例二:
using System.Runtime.InteropServices;
void MethodA([In][Out] ref double x) { }
void MethodB([Out][In] ref double x) { }
void MethodC([In, Out] ref double x) { }
[Conditional("DEBUG"), Conditional("TEST1")]
void TraceMethod()
{
// ...
}
命名上[DllImport]
等同于[DllImportAttribute]
,后者是属性真正的名字。
Attribute parameters
属性接收参数的顺序可以是顺位的、按名的、不按名的
(未完待续)