自定义Attribute
定义
/*****************************************************
** 命名空间: AtrributDemo
** 文 件 名:DeviceAttribute
** 内容简述:
** 版 本:V1.0
** 创 建 人:Byron
** 创建日期:2020/10/21 15:51:43
** 修改记录:
日期 版本 修改人 修改内容
*****************************************************/
using System;
namespace AtrributDemo
{
/// <summary>
///设备附加属性
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class DeviceAttribute : Attribute
{
/// <summary>
/// 设备类型
/// EX:海康相机,雷赛轴卡、欧姆龙感应器等
/// </summary>
public string DeviveType = "设备类型";
/// <summary>
/// 可复制
/// </summary>
public bool CopyEnable = false;
/// <summary>
/// 容器对象
/// </summary>
public bool Containers = false;
}
}
使用
/*****************************************************
** 命名空间: AtrributDemo
** 文 件 名:Camera
** 内容简述:
** 版 本:V1.0
** 创 建 人:Byron
** 创建日期:2020/10/21 15:58:20
** 修改记录:
日期 版本 修改人 修改内容
*****************************************************/
namespace AtrributDemo
{
[Device(DeviveType = "相机对象", CopyEnable = false)]
public class Camera
{
}
}
/*****************************************************
** 命名空间: AtrributDemo
** 文 件 名:DeviceContainers
** 内容简述:
** 版 本:V1.0
** 创 建 人:Byron
** 创建日期:2020/10/21 16:01:23
** 修改记录:
日期 版本 修改人 修改内容
*****************************************************/
namespace AtrributDemo
{
/// <summary>
/// 设备分类容器
/// </summary>
[Device(DeviveType = "设备分类容器", CopyEnable = false, Containers = true)]
internal class DeviceContainers
{
}
}
/*****************************************************
** 命名空间: AtrributDemo
** 文 件 名:MotionCard
** 内容简述:
** 版 本:V1.0
** 创 建 人:Byron
** 创建日期:2020/10/21 15:59:51
** 修改记录:
日期 版本 修改人 修改内容
*****************************************************/
namespace AtrributDemo
{
[Device(DeviveType = "运动控制卡对象", CopyEnable = false)]
internal class MotionCard
{
}
}
调用
调用主要是要用到**GetCustomAttributes()**进行反射;
using System;
using System.Reflection;
namespace AtrributDemo
{
internal class Program
{
private static void Main(string[] args)
{
Camera camera = new Camera();
MotionCard motionCard = new MotionCard();
DeviceContainers deviceContainers = new DeviceContainers();
WriteAtrribut(camera);
WriteAtrribut(motionCard);
WriteAtrribut(deviceContainers);
}
private static void WriteAtrribut(object camera)
{
System.Collections.Generic.IEnumerable<Attribute> cameraAttributes = camera.GetType().GetCustomAttributes();
foreach (Attribute item in cameraAttributes)
{
var attr = item as DeviceAttribute;
if (attr == null)
{
continue;
}
Console.WriteLine($" Device:{attr.DeviveType} Copy Enable: {attr.CopyEnable}, Containers: {attr.Containers}");
}
}
}
}
输出
.net 提供的部分使用方法
https://blog.youkuaiyun.com/FantasiaX/article/details/1627694
刘老师写得很好,本身.net就提供了很多的Attribute给我们使用,这些都是工具。
后续
Attribute在反射和Aop编程中的用法是十分广泛的。