特性的使用,校验long 长度
1 特性attribute定义:是一个类,编译时决定,不能使用变量
2 声明和使用attribute,AttributeUsage
3 运行中获取attribute:额外信息 额外操作
4 Remark封装、attribute验证
特性的使用:
1.定义T的扩展方法:Validate
public static bool Validate<T>(this T t)
{
Type type = t.GetType();
foreach (var prop in type.GetProperties())
{
if (prop.IsDefined(typeof(AbstractValidateAttribute), true))
{
object oValue = prop.GetValue(t);
foreach (AbstractValidateAttribute attribute in prop.GetCustomAttributes(typeof(AbstractValidateAttribute), true))
{
if (!attribute.Validate(oValue))
return false;
}
}
}
return true;
}
2. 定义校验基类AbstractValidateAttribute
和需要校验的long类型:LongAttribute
public abstract class AbstractValidateAttribute : Attribute
{
public abstract bool Validate(object oValue);
}
定义long校验类
[AttributeUsage(AttributeTargets.Property)]
public class LongAttribute : AbstractValidateAttribute
{
private long _Min = 0;
private long _Max = 0;
public LongAttribute(long min, long max)
{
this._Min = min;
this._Max = max;
}
public override bool Validate(object oValue)
{
return oValue != null
&& long.TryParse(oValue.ToString(), out long lValue)
&& lValue >= this._Min
&& lValue <= this._Max;
}
}
4.model 属性的校验:
public class Student
{
[Long(10000, 999999999999)]
public long QQ { get; set; }
}
Student student = new Student()
if (student.Validate())
{
Console.WriteLine("特性校验成功");
}
------------------------------第3方主动使用特性,特性才有作用,特性本身就一个类-----------------------------
public static void ManagerStudent<T>(T student) where T : Student
{
Console.WriteLine($"{student.Id}_{student.Name}");
student.Study();
student.Answer("123");
Type type = student.GetType();
if (type.IsDefined(typeof(CustomAttribute), true))
{
//type.GetCustomAttribute()
object[] oAttributeArray = type.GetCustomAttributes(typeof(CustomAttribute), true);
foreach (CustomAttribute attribute in oAttributeArray)
{
attribute.Show();
//attribute.Description
}
foreach (var prop in type.GetProperties())
{
if (prop.IsDefined(typeof(CustomAttribute), true))
{
object[] oAttributeArrayProp = prop.GetCustomAttributes(typeof(CustomAttribute), true);
foreach (CustomAttribute attribute in oAttributeArrayProp)
{
attribute.Show();
}
}
}
foreach (var method in type.GetMethods())
{
if (method.IsDefined(typeof(CustomAttribute), true))
{
object[] oAttributeArrayMethod = method.GetCustomAttributes(typeof(CustomAttribute), true);
foreach (CustomAttribute attribute in oAttributeArrayMethod)
{
attribute.Show();
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2015-01-14 2.HTML5 标准改变,准备工作
2015-01-14 1.html5 学习要求,Html 5发展历程