C# .NET - 编程概念 - C#特性
C#特性介绍和使用
使用特性,可以有效地将元数据或声明性信息与代码(程序集、类型、方法、属性等)相关联。 将特性与程序实体相关联后,可以在运行时使用反射这项技术查询特性。

C#特性和C#属性是两个不同的概念,需要分清。

特性具有以下属性:

特性向程序添加元数据。 元数据是程序中定义的类型的相关信息。 所有 .NET 程序集都包含一组指定的元数据,用于描述程序集中定义的类型和类型成员。 可以添加自定义特性来指定所需的其他任何信息。 有关详细信息,请参阅创建自定义特性 (C#)。
可以将一个或多个特性应用于整个程序集、模块或较小的程序元素(如类和属性)。
特性可以像方法和属性一样接受自变量。
程序可使用反射来检查自己的元数据或其他程序中的元数据。

使用特性

可以将特性附加到几乎任何声明中,尽管特定特性可能会限制可有效附加到的声明的类型。 在 C# 中,通过用方括号 ([ ]) 将特性名称括起来,并置于应用该特性的实体的声明上方以指定特性。

在此示例中,SerializableAttribute 特性用于将具体特征应用于类:
[Serializable]
public class SampleClass
{
// Objects of this type can be serialized.
}


下方示例声明了一个具有特性 DllImportAttribute 的方法:
[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static void SampleMethod();

特性的常见用途

下面列出了代码中特性的一些常见用途:

在 Web 服务中使用 WebMethod 特性标记方法,以指明方法应可通过 SOAP 协议进行调用。 有关详细信息,请参阅 WebMethodAttribute。
描述在与本机代码互操作时如何封送方法参数。 有关详细信息,请参阅 MarshalAsAttribute。
描述类、方法和接口的 COM 属性。
使用 DllImportAttribute 类调用非托管代码。
从标题、版本、说明或商标方面描述程序集。
描述要序列化并暂留类的哪些成员。
描述如何为了执行 XML 序列化在类成员和 XML 节点之间进行映射。
描述的方法的安全要求。
指定用于强制实施安全规范的特征。
通过实时 (JIT) 编译器控制优化,这样代码就一直都易于调试。
获取方法调用方的相关信息。

举个例子,代码如下:


namespace HovertreeAttributeNF
{
// Multiuse attribute.
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // Multiuse attribute.
]
public class Author : System.Attribute
{
string name;
public double version;

public Author(string name)
{
this.name = name;

// Default value.
version = 1.0;
}

public string GetName()
{
return name;
}
}

// Class with the Author attribute.
[Author("Hovertree")]
public class FirstClass
{
// ...
}

// Class without the Author attribute.
public class SecondClass
{
// ... 本类没设置作者特性 --何问起
}

// Class with multiple Author attributes.
[Author("Hovertree"), Author("Hewenqi", version = 2.0)]
public class ThirdClass
{
// ...
}

class TestAuthorAttribute
{
public static void Test()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));

}

private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);

// Using reflection.
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // Reflection.

// Displaying output.
foreach (System.Attribute attr in attrs)
{
if (attr is Author)
{
Author a = (Author)attr;
System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
}
}
}
}


internal class Program
{
static void Main(string[] args)
{
TestAuthorAttribute.Test();
System.Console.Read();
}
}
}
运行效果如下:
收藏 列表

评论:

导航