特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集、类型、方法、属性等)相关联。 特性与程序实体关联后,即可在运行时使用名为“反射”的技术查询特性。
特性具有以下属性:
-
特性可向程序中添加元数据。 元数据是有关在程序中定义的类型的信息。 所有的 .NET 程序集都包含指定的一组元数据,这些元数据描述在程序集中定义的类型和类型成员。 可以添加自定义特性,以指定所需的任何附加信息。
-
可以将一个或多个特性应用到整个程序集、模块或较小的程序元素(如类和属性)。
-
特性可以与方法和属性相同的方式接受参数。
-
程序可以使用反射检查自己的元数据或其他程序内的元数据。
示例:
关联类,实现Attribute
public class SpriteName {
public string spritname;
public string id;
public SpriteName(string _name,string _id)
{
spritname = _name;
id = _id;
}
}
public class SpriteNameAttribute : Attribute
{
public SpriteNameAttribute(string name,string id)
{
sprite = new SpriteName(name,id);
}
public SpriteName sprite
{
get; private set;
}
}
实现如下
public enum GameScene {
[Description("空")]
[SpriteName("1","null")]
None,
[Description("菜单")]
[SpriteName("2", "caidan")]
Menu,
[Description("游戏")]
[SpriteName("2", "game")]
Game
}
Description 是unity 已经写好得特性类。可以直接使用。
特性数据得获取一般通过反射来获取。实现如下
using System;
using System.ComponentModel;
using System.Reflection;
public class Util {
public static string GetDescription(Enum value)
{
Type enumType = value.GetType();
string name = Enum.GetName(enumType, value);
if (name != null)
{
FieldInfo fieldInfo = enumType.GetField(name);
if (fieldInfo != null)
{ DescriptionAttribute attr =
Attribute.GetCustomAttribute(fieldInfo,typeof(DescriptionAttribute), false) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
public static SpriteName GetSpriteName(Enum value){
Type enumType = value.GetType();
string name = Enum.GetName(enumType, value);
if (name != null)
{
FieldInfo fieldInfo = enumType.GetField(name);
if (fieldInfo != null)
{
SpriteNameAttribute attr =
Attribute.GetCustomAttribute(fieldInfo,typeof(SpriteNameAttribute), false) as SpriteNameAttribute;
if (attr != null)
{
return attr.sprite;
}
}
}
return null;
}
}
最后我们输出结果
Debug.Log(Util.GetDescription(GameScene.None));
Debug.Log(Util.GetDescription(GameScene.None));
Debug.Log(Util.GetSpriteName(GameScene.None).spritname);
Debug.Log(Util.GetSpriteName(GameScene.None).id);
结果如下:
其他得数据都可以通过这种方式来得到。
结论:特性类可以为一个枚举做描述信息。该信息能够在程序中得到并处理。 示例使用得是一组string。 也可以通过一个类,来传递跟多个数据信息。 对于一个类来说,如果用指定特性来修饰,还能注入数据。不过数据是固定的