首页 > 其他 > 详细

自定义特性

时间:2019-04-14 15:02:39      阅读:99      评论:0      收藏:0      [点我收藏+]

using System;

namespace Test
{


[AttributeUsage(AttributeTargets.Property)]
public class StringLengthtAttribute : Attribute
{
private int _maximumLength;
public StringLengthtAttribute(int maximumLength)
{
_maximumLength = maximumLength;
}

public int MaximumLength
{
get { return _maximumLength; }
}
public class People
{
[StringLengtht(8)]
public string Name { get; set; }

[StringLengtht(15)]
public string Description { get; set; }
}

 

public class ValidationModel
{

public void Validate(object obj)
{
var t = obj.GetType();

//由于我们只在Property设置了Attibute,所以先获取Property
var properties = t.GetProperties();
foreach (var property in properties)
{

//这里只做一个stringlength的验证,这里如果要做很多验证,需要好好设计一下,千万不要用if elseif去链接
//会非常难于维护,类似这样的开源项目很多,有兴趣可以去看源码。
if (!property.IsDefined(typeof(StringLengthtAttribute), false)) continue;

var attributes = property.GetCustomAttributes(true);
foreach (var attribute in attributes)
{
//这里的MaximumLength 最好用常量去做
var maxinumLength = (int)attribute.GetType().
GetProperty("MaximumLength").
GetValue(attribute);

//获取属性的值
var propertyValue = property.GetValue(obj) as string;
if (propertyValue == null)
throw new Exception("exception info");//这里可以自定义,也可以用具体系统异常类

if (propertyValue.Length > maxinumLength)//判断是不是超过了范围
throw new Exception(string.Format("属性{0}的值{1}的长度超过了{2}", property.Name, propertyValue, maxinumLength));
}
}

}
private static void Main(string[] args)
{
var people = new People()
{
Name = "qweasdzxcasdqweasdzxc",
Description = "description"
};
try
{
new ValidationModel().Validate(people);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
}

自定义特性

原文:https://www.cnblogs.com/mzcode/p/10705025.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!