是否可以使用数据注释属性来操作文本并在操作后返回一个新文本?
例如,我想验证一个字符串属性是否具有特殊字符或单词之间的多个空格,然后返回一个新字符串来替换原始属性的值。
使用数据注释有多大可能?
最佳答案
回答有点晚(2 年!),但是您可以修改在自定义 DataAnnotations 属性中验证的值。关键是覆盖 IsValid(Object, ValidationContext) ValidationAttribute 方法并执行一些反射魔法:
public class MyCustomValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext ctx)
{
// get the property
var prop = ctx.ObjectType.GetProperty(ctx.MemberName);
// get the current value (assuming it's a string property)
var oldVal = prop.GetValue(ctx.ObjectInstance) as string;
// create a new value, perhaps by manipulating the current one
var newVal = "???";
// set the new value
prop.SetValue(ctx.ObjectInstance, newVal);
return base.IsValid(value, ctx);
}
}
关于c# - 替换属性值的数据注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15541199/