C#学习笔记(十六):Attribute

时间:2023-11-25 16:58:14

Attribute可以为类或方法添加一些附加的信息,我们可以看看MSDN对Attribute的描述:

公共语言运行时允许你添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型、字段、方法和属性等。Attributes和Microsoft .NET Framework文件的元数据保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为。

在.NET中,Attribute被用来处理多种问题,比如序列化、程序的安全特征、防止即时编译器对程序代码进行优化从而代码容易调试等等。

内置Attribute

C#为我们提供了一些用来处理特定一些问题,我们接下来看看几个简单的特性:

Conditional

满足指定条件才会调用指定的方法。

 using System;
using System.Diagnostics; namespace Study
{
class Program
{
static void Main(string[] args)
{
Func(); Console.Read();
} [Conditional("DEBUG")]
private static void Func()
{
Console.WriteLine("I am a DEBUG function!");
}
}
}

在DEBUG模式下运行可以看见字符串输出,而在RELEASE模式下Func不会被调用。

Obsolete

可以指定类或方法是否已经被弃用,第一个参数为描述字符串,第二参数可以指定使用了类或方法时是否直接抛错。

 using System;
using System.Diagnostics; namespace Study
{
class Program
{
static void Main(string[] args)
{
Func(); Console.Read();
} [Obsolete("Don`t use this method!", true)]
private static void Func()
{
Console.WriteLine("I am a DEBUG function!");
}
}
}

呵呵,自己运行看看效果吧。

Serializable

使用这个特性可以实现类的序列化和反序列化效果。

 using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary; namespace Study
{
class Program
{
static void Main(string[] args)
{
Test test = new Test {name = "LiLei", age = }; byte[] bytes = ObjectToBytes(test);
Test test2 = BytesToObject(bytes) as Test; Console.WriteLine("name: " + test2.name + ", age: " + test2.age); Console.Read();
} public static byte[] ObjectToBytes(object obj)
{
using(MemoryStream ms = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
return ms.GetBuffer();
}
} public static object BytesToObject(byte[] Bytes)
{
using(MemoryStream ms = new MemoryStream(Bytes))
{
IFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(ms);
}
}
} [Serializable]
public class Test
{
public string name;
public int age;
}
}

注意可以使用两个静态序列化方法的对象必须是使用了Serializable特性的对象。

自定义Attribute

除了使用官方提供的特性以外,我们也可以根据自身的需求自定义一个自己的特性,具体使用方法如下:

  1. 新建一个类继承自System.Attribute,名称需要以Attribute结尾,比如VersionAttribute,我们可以给该类添加我们需要的属性。
  2. 使用时可用“[VersionAttribute]”或“[Version]”定义一个Attribute,同时可以设置属性。
  3. 具体使用时一般是使用反射的方式把我们需要的信息取出再进行处理。

给出几个不错的文章:

http://www.cnblogs.com/hyddd/archive/2009/07/20/1526777.html

http://www.cnblogs.com/luckdv/articles/1682488.html