C#自定义特性-SQL
语法
原则
自定义特性必须继承自System.Attribute类;
AttributeUsage属性来指定特性的使用范围和是否允许重复等;
在特性类中定义属性,这些属性将用于存储特性值。
示例
using System;// 定义一个自定义特性类
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CustomAttribute : Attribute
{// 特性属性public string Description { get; set; }public int Version { get; set; }// 特性构造函数public CustomAttribute(string description, int version){Description = description;Version = version;}
}// 使用自定义特性
[Custom("This is a sample class", 1)]
public class SampleClass
{[Custom("This is a sample method", 1)]public void SampleMethod(){// 方法实现}
}class Program
{static void Main(){// 获取SampleClass类的特性信息var classAttributes = typeof(SampleClass).GetCustomAttributes(typeof(CustomAttribute), false);foreach (CustomAttribute attr in classAttributes){Console.WriteLine($"Class Description: {attr.Description}, Version: {attr.Version}");}// 获取SampleMethod方法的特性信息var methodAttributes = typeof(SampleClass).GetMethod("SampleMethod").GetCustomAttributes(typeof(CustomAttribute), false);foreach (CustomAttribute attr in methodAttributes){Console.WriteLine($"Method Description: {attr.Description}, Version: {attr.Version}");}}
}
AttributeUsage中的AllowMultiple属性默认值为false,它决定同种特性类型的实例能否在同一个目标上多次使用,比如在类中的同一个属性上。
特性声明代码
using System;
using System.Reflection;namespace Model.Common
{/// <summary>/// 用于生成SQLServer数据库查询的like条件/// </summary>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]public class SqlLikeAttribute : Attribute{/// <summary>/// 数据库字段名/// </summary>public string FieldName { get; set; }public SqlLikeAttribute(string fidleName){FieldName = fidleName;}}/// <summary>/// 用于生成SQLServer数据库查询的>、>=、<、<==、=条件/// </summary>[AttributeUsage(AttributeTargets.Property,AllowMultiple = false)]public class SqlRangeAttribute: Attribute{/// <summary>/// 数据库字段名/// </summary>public string FieldName { get; set; }/// <summary>/// 取值范围:>、>=、<、<==、=/// </summary>public string Range { get; set; }public SqlRangeAttribute(string fidleName, string range){FieldName = fidleName;Range= range;}}/// <summary>/// 用于生成SQLServer数据库查询的between条件/// </summary>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]public class SqlBetweenAttribute : Attribute{/// <summary>/// 数据库字段名/// </summary>public string FieldName { get; set; }/// <summary>/// 查询条件实体中的另一个字段名/// </summary>public string AnotherFieldName { get; set; }/// <summary>/// 是否是开始/// </summary>public bool IsStart { get; set; }public Object Value { get; set; }public SqlBetweenAttribute(string fidleName, string anotherFieldName, bool start = true){FieldName = fidleName;AnotherFieldName = anotherFieldName;IsStart = start;}}/// <summary>/// 用于生成SQLServer数据库查询的条件,有SqlIgnoreAttribute修饰的属性直接忽略掉/// </summary>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]public class SqlIgnoreAttribute : Attribute{}/// <summary>/// 测试/// </summary>public class AttributeTest{public static void Test(){TestModel testModel = new TestModel(){ID = 1,Name = "test",Begin = DateTime.Now,End = DateTime.Now.AddDays(1),};Type type = testModel.GetType();PropertyInfo[] infos = type.GetProperties();foreach (PropertyInfo info in infos){SqlBetweenAttribute attr = (SqlBetweenAttribute)info.GetCustomAttribute(typeof(SqlBetweenAttribute), false);if (attr != null){string field = attr.FieldName;}}}}public class TestModel{public int ID { get; set; }public string Name { get; set; }[SqlBetween("field", "End")]public DateTime Begin { get; set; }[SqlBetween("field", "Begin", false)]public DateTime End { get; set; }}
}
使用特性
/// <summary>/// 从实体中获取属性值不为空的属性和值,用于数据库Select的Where条件/// 暂时只支持,int、string、double、DateTime/// 要求数值类型默认为-1/// </summary>/// <param name="data"></param>/// <param name="prefix">前缀</param>/// <returns></returns>public static List<string> GetPropertyValueNotNullForSelectWhere(this object data, string prefix){string item = "";List<string> items = new List<string>();Dictionary<string, SqlBetweenAttribute> dic = new Dictionary<string, SqlBetweenAttribute>();DateTime dateTime = new DateTime(1, 1, 1, 0, 0, 0);PropertyInfo[] propertyInfos = data.GetType().GetProperties();foreach (PropertyInfo propertyInfo in propertyInfos){if (propertyInfo.Name.ToUpper() == "ID")continue;item = "";object obj = propertyInfo.GetValue(data, null);switch (propertyInfo.PropertyType.FullName){case "System.Int32":if (Convert.ToInt32(obj) == -1)continue;item = $" and {prefix}{propertyInfo.Name}={Convert.ToInt32(obj)}";break;case "System.String":if (Convert.ToString(obj) == "")continue;item = $" and {prefix}{propertyInfo.Name}='{Convert.ToString(obj)}'";break;case "System.Double":if (Convert.ToDouble(obj) == -1)continue;item = $" and {prefix}{propertyInfo.Name}={Convert.ToDouble(obj)}";break;case "System.Decimal":if (Convert.ToDecimal(obj) == -1)continue;item = $" and {prefix}{propertyInfo.Name}={Convert.ToDecimal(obj)}";break;case "System.DateTime":obj = propertyInfo.GetValue(data, null);if (Convert.ToDateTime(obj) == dateTime)continue;item = $" and {prefix}{propertyInfo.Name}='{Convert.ToDateTime(obj)}'";break;}//if(!CheckAttrSqlBetween(propertyInfo, obj, ref dic, ref item))// continue;CheckAttrSqlRange(propertyInfo, obj, ref item, prefix);CheckAttrSqlLike(propertyInfo, obj, ref item, prefix);if (!CheckAttrSqlIgnore(propertyInfo, obj, ref item))continue;items.Add(item);}return items;}/// <summary>/// 检查属性是否被SqlBetween特性修饰,并处理/// </summary>/// <param name="propertyInfo">实体的属性对象</param>/// <param name="obj">属性的值</param>/// <param name="dic">暂存特性的字典</param>/// <param name="item"></param>/// <returns>true 表示需要把item加到List<string>中</returns>static bool CheckAttrSqlBetween(PropertyInfo propertyInfo, object obj, ref Dictionary<string, SqlBetweenAttribute> dic, ref string item){SqlBetweenAttribute attr = (SqlBetweenAttribute)propertyInfo.GetCustomAttribute(typeof(SqlBetweenAttribute), false);if (attr == null)return true;attr.Value = obj;if (!dic.ContainsKey(attr.AnotherFieldName)){ //缺少另外一个,先缓存dic.Add(attr.AnotherFieldName, attr);return false;}else{SqlBetweenAttribute _attr = dic[attr.AnotherFieldName];dic.Remove(attr.AnotherFieldName);SqlBetweenAttribute attrb = attr.IsStart ? attr : _attr;SqlBetweenAttribute attre = attr.IsStart ? _attr : attr;switch (propertyInfo.PropertyType.FullName){case "System.Int32":case "System.Double":case "System.Decimal":item = $" and {attr.FieldName} between {attrb.Value} and {attre.Value}";break;case "System.String":case "System.DateTime":item = $" and {attr.FieldName} between '{attrb.Value}' and '{attre.Value}'";break;}return true;}}/// <summary>/// 检查属性是否被SqlRange特性修饰,并处理/// </summary>/// <param name="propertyInfo"></param>/// <param name="obj"></param>/// <param name="item"></param>/// <returns></returns>static void CheckAttrSqlRange(PropertyInfo propertyInfo, object obj, ref string item, string prefix){SqlRangeAttribute attr = (SqlRangeAttribute)propertyInfo.GetCustomAttribute(typeof(SqlRangeAttribute), false);if (attr == null)return;switch (propertyInfo.PropertyType.FullName){case "System.Int32":case "System.Double":case "System.Decimal":item = $" and {prefix}{attr.FieldName} {attr.Range} {obj} ";break;case "System.String":case "System.DateTime":item = $" and {prefix}{attr.FieldName} {attr.Range} '{obj}' ";break;}return;}/// <summary>/// 检查属性是否被SqlLike特性修饰,并处理/// </summary>/// <param name="propertyInfo"></param>/// <param name="obj"></param>/// <param name="item"></param>static void CheckAttrSqlLike(PropertyInfo propertyInfo, object obj, ref string item, string prefix){SqlLikeAttribute attr = (SqlLikeAttribute)propertyInfo.GetCustomAttribute(typeof(SqlLikeAttribute), false);if (attr == null)return;switch (propertyInfo.PropertyType.FullName){case "System.String":item = $" and ({prefix}{attr.FieldName} like '%{obj}%' or {prefix}{attr.FieldName}='{obj}') ";break;}return;}/// <summary>/// 检查属性是否被SqlIgnoreAttribute特性修饰,如果修饰则不加入到Where条件中/// </summary>/// <param name="propertyInfo"></param>/// <param name="obj"></param>/// <param name="item"></param>/// <returns></returns>static bool CheckAttrSqlIgnore(PropertyInfo propertyInfo, object obj, ref string item){SqlIgnoreAttribute attr = (SqlIgnoreAttribute)propertyInfo.GetCustomAttribute(typeof(SqlIgnoreAttribute), false);if (attr == null)return true;elsereturn false;}
相关文章:
C#自定义特性-SQL
语法 原则 自定义特性必须继承自System.Attribute类; AttributeUsage属性来指定特性的使用范围和是否允许重复等; 在特性类中定义属性,这些属性将用于存储特性值。 示例 using System;// 定义一个自定义特性类 [Attribute…...
协方差矩阵及其计算方法
协方差矩阵(Covariance Matrix)是一个描述多维数据特征之间相互关系的矩阵,广泛应用于统计学和机器学习中。它用于表示各个特征之间的协方差,是分析多维数据分布和特征依赖性的重要工具。 什么是协方差矩阵? 协方差矩…...

【OH】openHarmony开发环境搭建(基于windows子系统WSL)
前言 本文主要介绍基于windows子系统WSL搭建openHarmony开发环境。 WSL与Vmware虚拟机的区别,可以查看WSL与虚拟机的区别 更详细的安装配置过程可参考微软官网: 安装 WSL 前提 以下基于windows 111专业版进行配置,windows 10应该也是可以…...
Visual Studio Code 端口转发功能详解
Visual Studio Code 端口转发功能详解 引言 Visual Studio Code(简称 VS Code)是一个功能强大的源代码编辑器,它支持多种编程语言的语法高亮、智能代码补全、自定义快捷键、代码重构等特性。除了这些基本功能外,VS Code 还提供了…...

Android Framework AMS(14)ContentProvider分析-1(CP组件应用及开机启动注册流程解读)
该系列文章总纲链接:专题总纲目录 Android Framework 总纲 本章关键点总结 & 说明: 说明:本章节主要解读ContentProvider组件的基本知识。关注思维导图中左上侧部分即可。 有了前面activity组件分析、service组件分析、广播组件分析的基…...
Three.js PBR材质
本文将详细介绍Three.js中的PBR(Physically Based Rendering)材质,包括PBR的基本概念、适用场景、PBR材质的构建以及一些高级应用技巧。 1. PBR(Physically Based Rendering)基本概念 PBR,即Physically B…...

智谱AI清影升级:引领AI视频进入音效新时代
前几天智谱推出了新清影,该版本支持4k、60帧超高清画质、任意尺寸,并且自带音效的10秒视频,让ai生视频告别了"哑巴时代"。 智谱AI视频腾空出世,可灵遭遇强劲挑战!究竟谁是行业翘楚?(附测评案例)之前智谱出世那时体验了一…...

嵌入式硬件电子电路设计(五)MOS管详解(NMOS、PMOS、三极管跟mos管的区别)
引言:在我们的日常使用中,MOS就是个纯粹的电子开关,虽然MOS管也有放大作用,但是几乎用不到,只用它的开关作用,一般的电机驱动,开关电源,逆变器等大功率设备,全部使用MOS管…...
Centos 9 安装 PostgreSQL 16 并支持远程访问
仅列出核心操作,可以解决使用过程中遇到的访问问题。 1 安装 使用dnf源安装 sudo dnf module -y install postgresql:16 2 配置文件夹权限 使用root权限操作 sudo chown postgres:postgres /var/lib/pgsql/datasudo chmod -R 0750 /var/lib/pgsql/data 3 初…...

Dubbo源码解析(三)
一、Dubbo整合Spring启动流程 Dubbo的使用可以不依赖Spring,但是生产环境中Dubbo都是整合到Spring中一起使用,所以本章就解析Dubbo整合Spring的启动流程 一、传统的xml解析方式 一、Dubbo配置解析流程 在Java 中,一切皆对象。在JDK 中使用…...

HarmonyOS Next星河版笔记--界面开发(5)
1.字符串 1.1.字符串拼接 作用:把两个或多个字符串,拼成一个字符串。(通常是用来拼接字符串和变量) hello world > helloworld 加好作用:拼接 let name:string 小明 console.log(简介信息,名字是 name) …...

Spring Boot3 实战案例合集上线了
Spring Boot3实战案例合集...

在Ubuntu 24.04 LTS上安装飞桨PaddleX
前面我们介绍了《在Windows用远程桌面访问Ubuntu 24.04.1 LTS》本文接着介绍安装飞桨PaddleX。 PaddleX 3.0 是基于飞桨框架构建的一站式全流程开发工具,它集成了众多开箱即用的预训练模型,可以实现模型从训练到推理的全流程开发,支持国内外多…...
Homebrew 命令大全
Homebrew 是 macOS 和 Linux 系统上的一个流行的包管理器,它可以帮助用户轻松地安装、更新和管理软件包。以下是一些常用的 Homebrew 命令: 安装 Homebrew 如果你还没有安装 Homebrew,可以使用以下命令在 macOS 上进行安装: /b…...

Docker+Django项目部署-从Linux+Windows实战
一、概述 1. 什么是Docker Docker 是一个开源的应用容器引擎,支持在win、mac、Linux系统上进行安装。可以帮助我们在一台电脑上创建出多个隔离的环境,比传统的虚拟机极大的节省资源 。 为什么要创建隔离的环境? 假设你先在有一个centos7.…...

前端 JS 实用操作总结
目录 1、重构解构 1、数组解构 2、对象解构 3、...展开 2、箭头函数 1、简写 2、this指向 3、没有arguments 4、普通函数this的指向 3、数组实用方法 1、map和filter 2、find 3、reduce 1、重构解构 1、数组解构 const arr ["唐僧", "孙悟空&quo…...
11.15 机器学习-集成学习方法-随机森林
# 机器学习中有一种大类叫**集成学习**(Ensemble Learning),集成学习的基本思想就是将多个分类器组合,从而实现一个预测效果更好的集成分类器。集成算法可以说从一方面验证了中国的一句老话: # 三个臭皮匠,…...

【SQL】E-R模型(实体-联系模型)
目录 一、介绍 1、实体集 定义和性质 属性 E-R图表示 2. 联系集 定义和性质 属性 E-R图表示 一、介绍 实体-联系数据模型(E-R数据模型)被开发来方便数据库的设计,它是通过允许定义代表数据库全局逻辑结构的企业模式…...
C/C++静态库引用过程中出现符号未定义的处理方式
问题背景: 在接入新库(静态库)时遇到了符号未定义问题,并发现改变静态库的链接顺序可以解决问题。 问题根源: 静态库是由 .o 文件拼接而成的,链接静态库时,链接器以 .o 文件为单位进行处理。链接…...

『VUE』27. 透传属性与inheritAttrs(详细图文注释)
目录 什么是透传属性(Forwarding Attributes)使用条件唯一根节点禁用透传属性继承总结 欢迎关注 『VUE』 专栏,持续更新中 欢迎关注 『VUE』 专栏,持续更新中 什么是透传属性(Forwarding Attributes) 在 V…...

手游刚开服就被攻击怎么办?如何防御DDoS?
开服初期是手游最脆弱的阶段,极易成为DDoS攻击的目标。一旦遭遇攻击,可能导致服务器瘫痪、玩家流失,甚至造成巨大经济损失。本文为开发者提供一套简洁有效的应急与防御方案,帮助快速应对并构建长期防护体系。 一、遭遇攻击的紧急应…...

Appium+python自动化(十六)- ADB命令
简介 Android 调试桥(adb)是多种用途的工具,该工具可以帮助你你管理设备或模拟器 的状态。 adb ( Android Debug Bridge)是一个通用命令行工具,其允许您与模拟器实例或连接的 Android 设备进行通信。它可为各种设备操作提供便利,如安装和调试…...

2025年能源电力系统与流体力学国际会议 (EPSFD 2025)
2025年能源电力系统与流体力学国际会议(EPSFD 2025)将于本年度在美丽的杭州盛大召开。作为全球能源、电力系统以及流体力学领域的顶级盛会,EPSFD 2025旨在为来自世界各地的科学家、工程师和研究人员提供一个展示最新研究成果、分享实践经验及…...

LeetCode - 394. 字符串解码
题目 394. 字符串解码 - 力扣(LeetCode) 思路 使用两个栈:一个存储重复次数,一个存储字符串 遍历输入字符串: 数字处理:遇到数字时,累积计算重复次数左括号处理:保存当前状态&a…...
系统设计 --- MongoDB亿级数据查询优化策略
系统设计 --- MongoDB亿级数据查询分表策略 背景Solution --- 分表 背景 使用audit log实现Audi Trail功能 Audit Trail范围: 六个月数据量: 每秒5-7条audi log,共计7千万 – 1亿条数据需要实现全文检索按照时间倒序因为license问题,不能使用ELK只能使用…...

HTML 列表、表格、表单
1 列表标签 作用:布局内容排列整齐的区域 列表分类:无序列表、有序列表、定义列表。 例如: 1.1 无序列表 标签:ul 嵌套 li,ul是无序列表,li是列表条目。 注意事项: ul 标签里面只能包裹 li…...

使用 SymPy 进行向量和矩阵的高级操作
在科学计算和工程领域,向量和矩阵操作是解决问题的核心技能之一。Python 的 SymPy 库提供了强大的符号计算功能,能够高效地处理向量和矩阵的各种操作。本文将深入探讨如何使用 SymPy 进行向量和矩阵的创建、合并以及维度拓展等操作,并通过具体…...
Java + Spring Boot + Mybatis 实现批量插入
在 Java 中使用 Spring Boot 和 MyBatis 实现批量插入可以通过以下步骤完成。这里提供两种常用方法:使用 MyBatis 的 <foreach> 标签和批处理模式(ExecutorType.BATCH)。 方法一:使用 XML 的 <foreach> 标签ÿ…...

Golang——9、反射和文件操作
反射和文件操作 1、反射1.1、reflect.TypeOf()获取任意值的类型对象1.2、reflect.ValueOf()1.3、结构体反射 2、文件操作2.1、os.Open()打开文件2.2、方式一:使用Read()读取文件2.3、方式二:bufio读取文件2.4、方式三:os.ReadFile读取2.5、写…...

MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
macos brew国内镜像加速方法 brew install 加速formula.jws.json下载慢加速 🍺 最新版brew安装慢到怀疑人生?别怕,教你轻松起飞! 最近Homebrew更新至最新版,每次执行 brew 命令时都会自动从官方地址 https://formulae.…...