데이터 주석 속성을 사용하여 텍스트를 조작하고 조작 후 새 값을 반환 할 수 있습니까?속성의 값을 대체하기위한 데이터 주석?
예를 들어 단어 사이에 특수 문자 또는 여러 공백이있는 문자열 속성의 유효성을 검사 한 다음 원래 속성의 값을 바꾸기 위해 새 문자열을 반환하고 싶습니다.
데이터 주석을 사용하는 것이 가능한가요?
데이터 주석 속성을 사용하여 텍스트를 조작하고 조작 후 새 값을 반환 할 수 있습니까?속성의 값을 대체하기위한 데이터 주석?
예를 들어 단어 사이에 특수 문자 또는 여러 공백이있는 문자열 속성의 유효성을 검사 한 다음 원래 속성의 값을 바꾸기 위해 새 문자열을 반환하고 싶습니다.
데이터 주석을 사용하는 것이 가능한가요?
데이터 주석이 아니라 속성입니다.
그래서 그래 이미 여기에서 논의 된 다양한 방법을 통해 :
How to get and modify a property value through a custom Attribute? Change Attribute's parameter at runtime
그것은 '당신이 할 수없는'
이Corak의 제안이에 하위 클래스에 검증에서 다양한 솔루션을주의하는 것이 재미있다 가장 좋은 방법. 그러나 기본 클래스를 작성할 수 있으며 리플렉션을 사용하면 멤버 유형의 내용으로 원하는 모든 작업을 수행 할 수 있습니다.
답할 시간이 조금 모자라지만 (2 년), 맞춤 DataAnnotations 속성에서 유효성을 검사 할 값을 수정할 수 있습니다. 열쇠는 ValidationAttribute의 IsValid(Object, ValidationContext) 메서드를 재정의하고 약간의 반사 마법 수행 : Dado.ComponentModel.Mutations
이 예는 잘못된 문자가 제거되었는지 확인합니다 : 여기
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);
}
}
아마 당신이 기대하고 무엇을해야하는 패키지입니다 문자열. 검증을 소개하지는 않지만 System.ComponentModel.Annotations
은 Dado.ComponentModel.Mutations
과 함께 사용할 수 있습니다.
public partial class ApplicationUser
{
[ToLower, RegexReplace(@"[^a-z0-9_]")]
public virtual string UserName { get; set; }
}
// Then to preform mutation
var user = new ApplicationUser() {
UserName = "[email protected]_speed.01!"
}
new MutationContext<ApplicationUser>(user).Mutate();
Mutate()
에 대한 호출 후, user.UserName
는 mx_speed01
로 변이 될 것입니다.
get/set 부분에서 수행 할 수 없습니까? 'Property {get {return _Property.Replace (badChar, goodChar)}; }}' – Corak
더 나은 접근 방식은 DataBinder라고 생각합니다. http://stackoverflow.com/a/1734025/7720 – Romias