C#:实体类中做数据验证
主要是在实体类中验证
using System;
namespace Jone.Function.attribute
{
/// <summary>
/// 附加在数据实体用于描述如何验证合法性
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidateAttribute : Attribute
{
private bool _allowNull = true;
private string _regEx;
private string _description;
private string _ValidateType;
private string _instruction;
#region 方法
public ValidateAttribute()
{
}
public ValidateAttribute(bool AllowNull)
{
_allowNull = AllowNull;
}
public ValidateAttribute(bool AllowNull, string ValidateType)
{
_allowNull = AllowNull;
_ValidateType = ValidateType;
}
#endregion
#region 属性
/// <summary>
/// 描述
/// </summary>
public string Description
{
get { return _description; }
set { _description = value; }
}
/// <summary>
/// 验证类型
/// </summary>
public string ValidateType
{
get
{
return _ValidateType;
}
set
{
_ValidateType = value;
}
}
/// <summary>
/// 是否可以空
/// </summary>
public bool AllowNull
{
get
{
return _allowNull;
}
set
{
_allowNull = value;
}
}
/// <summary>
/// 用于验证的正则表达式
/// </summary>
public string RegEx
{
get
{
return _regEx;
}
set
{
_regEx = value;
}
}
/// <summary>
/// 对于正确格式的描述
/// </summary>
public string Instruction
{
get
{
return _instruction;
}
set
{
_instruction = value;
}
}
#endregion
}
#region 使用示例
//public class 使用示例
//{
// public 使用示例()
// {
// }
// private int _id;
// private string _name;
// //[Validate(RegEx = "^\\d{17}(http://www.cnblogs.com/luomingui/admin/file:///d|x)$", Description = "身份证号码")]
// [Validate(RegEx = "", Description = "")]
// public int id
// {
// set { _id = value; }
// get { return _id; }
// }
// [Validate(AllowNull = false, Description = "姓名")]
// public string name
// {
// set { _name = value; }
// get { return _name; }
// }
//}
#endregion
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)